刚好这段时间没什么事,抓紧时间看了下几个kotlin的开源项目,在这里做个自我汇总。
kotlin可以完全兼容Java,以前积累的Java库和Java世界很好用的开源框架,比如retrofit,rxjava,dagger,butterknife可以直接拿过来用。所以有信心的话可以考虑新项目直接从kotlin开发,当然项目评估的时候,要注意时间,毕竟新语言刚开始用的不会像Java那么熟练
Android的话可以用AS3.0(注意还不是稳定版),其实AS3.0又增强了不少,比如:Android Profiler, Mobile File Explorer, 所以我现在开发Java项目也会直接用AS3.0。
比如一个android library module的配置如下
apply plugin: 'com.android.library' apply plugin: 'kotlin-android' apply plugin: 'kotlin-android-extensions' android { ... sourceSets { main.java.srcDirs += 'src/main/kotlin' } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) compile 'com.android.support:appcompat-v7:24.2.1' compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"//这里上面已经有定义 }Anko是kotlin开源的一个工具库,可以加快和简化安卓开发,值得去关注和研究。
使用object就可以了,比如:
object JsonUtils { @Throws(IOException::class) fun readNullSafeString(reader: JsonReader): String? { if (reader.peek() == JsonToken.NULL) { reader.nextNull() return null } else { return reader.nextString() } } } //使用方式 JsonUtils.readNullSafeString(...)当一个类实现一个接口,需要实现接口中的方法,有些时候你想把接口交给别的类代理去做,写法:
class A(private var edit: EditableImpl):Editable by edit{} //使用基础构造函数中的edit来代理Editable接口。因为kotlin可以定义top-level函数,比如:
//example.kt package com.sherchen.example fun print(){}在其他地方可以直接使用
//demo.kt package com.sherchen.example class Test(){ fun test(){ print() } }这点像java的static import 但是kotlin不需要import,更像是C/C++的函数(非类的成员函数)
因为kotlin代码中无处不在的lambda和闭包,包括Standard库中的apply,also,with等等函数都使用了大量闭包,所以如果要想玩转kotlin,必须熟悉和熟练使用闭包,比如:
//闭包你可以理解为设计模式中的模板方法和命令模式,非常好用。 inline fun <T : Child, R> T.use(block: (T) -> R): R { var done = false try { return block(this) } catch (e: Exception) { done = true this.done() throw e } finally { if (!done) { this.done() } } }有时候需要定义一个数据类解析服务端返回的数据,而kotlin专门提供了data class来做,为什么不用呢,比如:
data class FuckGoods( val _id: String, val createdAt: String, val desc: String, val images: Array<String>, val publishedAt: String, val source: String, val type: String, val url: String, val used: Boolean, val who: String ){ fun hasImg():Boolean { return images != null } fun create() = createdAt.substring(0,10) }在Java中没有区分,但是在kotlin中要注意
class A { private var a:Int? = null class B{//Nested Class } } class A { private var a:Int? = null inner class B {//Inner class fun test(){ //所以内部类可以直接访问外部类的成员。 print(a) } } }inner classs的特点是:拥有外部类对象的引用,所以可以访问外部类的成员。 NOTE:因为内部类拥有外部类对象的引用,所以需要注意内存泄漏的问题
因为在kotlin中,属性必须初始化,比如
class A{ private var a: Int? = null }但是有时候,我们需要等会儿再初始化(这跟Java不一定,因为Java有默认值,所以属性不需要强制初始化),比如: 写Test,使用@Inject 比如使用dagger时,@Inject
@Inject lateinit var mPresenter : RandomPresenter比如使用Butterknife
@BindView(R2.id.title) lateinit var title: TextView可以有两种选择,基础构造函数和第二级构造函数。但是需要注意基础构造函数只能定义参数列表,要做初始化的操作,可以用
init {//这里做初始化操作 }第二级构造函数就和Java的差不多了。
我汇总了比较实用的kotlin开源项目,方便以后查阅,在阅读过程中加了一些注释,代码地址:MyKotlins