Kotlin学习资料

Stuck on Java 6(.5)ish
1)No javax.time Use ThreeTenBP / ThreeTenABP
2)No streams Use backport or RxJava
3)No lambdas, method refs, non-capturing anon class Use Retrolambda
4)No try-with-resources minSdkVersion=19 or Retrolambda
Java language restrictions and problems:
1)Inability to add methods to platform types (“Util” hell)
2)Nullability problems
3)General verbosity of common idioms
Android API design problems
1) Inheritance party
2) Nullability everywhere
3) Ceremony of APIs

1)Inability to add methods to platform types (“Util” hell)
Kotlin, similar to C# and Gosu, provides the ability to extend a class with new functionality without having to inherit from the class or use any type of design pattern such as Decorator. This is done via special declarations called extensions. Kotlin supports extension functions and extension properties. kotlin doc
由于java不能为平台现有类型添加方法,所以必须通过继承现有类型,装饰设计模式或者Util工具类的形式完成方法的拓展。Kotlin可以为现有的类型拓展方法和属性。

拓展方法:

1
2
3
4
5
6
7
8
fun MutableList<Int>.swap(x: Int, y: Int) {
val tmp = this[x]
this[x] = this[y]
this[y] = tmp
}

val l = mutableListOf(1, 2, 3)
l.swap(0, 2)

拓展属性:

1
2
val <T> List<T>.lastIndex: Int
get() = size - 1

扩展并不能真正的修改被拓展的类,不能在被拓展类内插入新成员,仅仅是通过该类的实例去调用这个新方法或是通过get/set方法获取新的属性值。更多内容

2)Nullability problems
kotlin允许声明空指针安全的变量,并提供异常简便的判空或非空的操作。

1
var str:String? = null

If not null:

1
2
3
4
5
6
7
val files = File("Test").listFiles()
println(files?.size)

val data = ...
data?.let {
...
}

If not null and else:

1
2
val files = File("Test").listFiles()
println(files?.size ?: "empty")

if null

1
2
val data = ...
val email = data["email"] ?: throw IllegalStateException("Email is missing!")

3)General verbosity of common idioms
java语言惯用语法普遍冗余繁琐,而Kotlin在语法上相比Java语言做到了全方位地简洁。

jake wharton:advancing development with kotlin
jake wharton演讲视频
kotlin官方文档
原版离线PDF
Kotlin for android Developers WangJie的中文翻译

文章目录