您的位置:首页 > 其它

kotlin深入1

2017-06-06 17:20 155 查看

前言

刚好这段时间没什么事,抓紧时间看了下几个kotlin的开源项目,在这里做个自我汇总。

1.兼容性

kotlin可以完全兼容Java,以前积累的Java库和Java世界很好用的开源框架,比如retrofit,rxjava,dagger,butterknife可以直接拿过来用。所以有信心的话可以考虑新项目直接从kotlin开发,当然项目评估的时候,要注意时间,毕竟新语言刚开始用的不会像Java那么熟练

2.开发工具

Android的话可以用AS3.0(注意还不是稳定版),其实AS3.0又增强了不少,比如:Android Profiler, Mobile File Explorer, 所以我现在开发Java项目也会直接用AS3.0。

3.标准模板

3.1 gradle-wrapper.properties

#Mon Jun 05 10:00:54 CST 2017
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
#注意要使用gradle-4.0,可以使用default,也可以下载下来
distributionUrl=https\://services.gradle.org/distributions/gradle-4.0-milestone-1-all.zip


3.2 工程根目录的build.gradle

uildscript {
ext.kotlin_version = '1.1.2-4'//最新版本号
//    ext.kotlin_version = '1.1.2'
repositories {
jcenter()
maven {
url 'https://maven.google.com'//AS 3.0一定要加
}
}
dependencies {
classpath 'com.android.tools.build:gradle:3.0.0-alpha3'//最新版本
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}


3.3 module的build.gradle

比如一个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"//这里上面已经有定义
}


4.使用anko

Anko是kotlin开源的一个工具库,可以加快和简化安卓开发,值得去关注和研究。

5.一些心得

5.1 写一个工具库

使用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(...)


5.2 使用by代理接口

当一个类实现一个接口,需要实现接口中的方法,有些时候你想把接口交给别的类代理去做,写法:

class A(private var edit: EditableImpl):Editable by edit{}
//使用基础构造函数中的edit来代理Editable接口。


5.3 top-level函数的使用

因为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++的函数(非类的成员函数)

5.4 必须熟悉lambda和闭包

因为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()
}
}
}


5.5 定义Entity类

有时候需要定义一个数据类解析服务端返回的数据,而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)

}


5.6类型使用

Kclass<T> == T::class
Class<T> == T::class.java


5.7 Nested Class和Inner Class

在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:因为内部类拥有外部类对象的引用,所以需要注意内存泄漏的问题

5.8 使用lateinit

因为在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


5.9 注意使用构造函数

可以有两种选择,基础构造函数和第二级构造函数。但是需要注意基础构造函数只能定义参数列表,要做初始化的操作,可以用

init {//这里做初始化操作
}


第二级构造函数就和Java的差不多了。

5.10 抛出异常。

@Throws(IOException::class)
override fun write(writer: JsonWriter, value: Country) {
throw UnsupportedOperationException()
}


最后

我汇总了比较实用的kotlin开源项目,方便以后查阅,在阅读过程中加了一些注释,代码地址:MyKotlins
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  开源项目 kotlin