本文是学习Kotlin的惯用语法和代码风格,与Java的语法和代码风格有一些相同,也有一些不同。
创建DTO’s(POJOs/POCOs)数据类(Creating DTOs (POJOs/POCOs))
1 | data class Customer(val name: String, val email: String) |
这里的Customer是数据类,在Kotlin中,会自动为Customer类生成以下方法
- 给所有属性添加
getter
方法,如果是var类型的话会添加setter
方法 equals()
haseCode()
toString()
copy()
- 给所有属性添加
component1()
,component2()
,…
函数参数默认值(Default values for function parameters)
可以为函数的参数设置默认值1
fun foo(a: Int = 0, b: String = "") { ... }
过滤list(Filtering a list)
使用扩展函数filter
来过滤list1
val positives = list.filter { x -> x > 0 }
或者用it
来替换x1
val positives = list.filter { it > 0 }
判断实例(Instance Checks)
通过用is来判断是否属于某个实例1
2
3
4
5when (x) {
is Foo -> ...
is Bar -> ...
else -> ...
}
遍历map/list(Traversing a map/list of pairs)
1 | for ((k, v) in map) { |
其中k和v可用任意命名
只读list
/map
(Read-only list/map)
只读就是设置为常量1
2val list = listOf("a", "b", "c")
val map = mapOf("a" to 1, "b" to 2, "c" to 3)
访问map(Accessing a map)
对map的使用1
2println(map["key"])
map["key"] = value
延时加载(Lazy property)
lazy 用于延时加载,即第一次使用时才执行初始化的操作。1
2
3val p: String by lazy {
// compute the string
}
扩展函数(Extension Functions)
1 | fun String.spcaceToCamelCase() { ... } |
前面有提到filter
扩展函数,扩展函数就是创建可直接使用的方法,例如我要创建一个可直接使用的toast方法,可以这样写1
2
3
4
fun Context.toast(content: String?) {
Toast.makeText(this, content, Toast.LENGTH_SHORT).show()
}
调用的时候1
2
3
4// activity里面
toast("扩展函数")
// 有context的时候
mContext.toast("扩展函数")
创建单例(Creating a singleton)
Kotlin创建单例模式就比较简单了1
2
3object Resource {
val name = "Name"
}
如果不为空则…的简写(If not null shorthand)
1 | val files = File("Test").listFiles() |
如果不为空则…否则…的简写(If not null and else shorthand)
1 | val files = File("Test").listFiles() |
如果为空,则执行语句(Executing a statement if null)
使用?:
符号,为空时执行语句1
2
3
4
5val data = ...
val email = data["email"] ?: throw IllegalStateException("Email is missing!")
val name = data["name"] ?:let{
...
}
如果不为空,则执行语句(Execute if not null)
使用?
符号,加非空判断,.let{ }
是不为空的时候执行1
2
3
4
5val data = ...
data?.let {
... // 如果不为空,请执行此块操作
}
返回 when 判断(Return on when statement)
返回的时候可以直接用when
表达式返回值1
2
3
4
5
6
7
8fun transform(color: String): Int {
return when (color) {
"Red" -> 0
"Green" -> 1
"Blue" -> 2
else -> throw IllegalArgumentException("Invalid color param value")
}
}
如果一个函数只有一个并且是表达式函数体并且是返回类型自动推断的话,可以直接等于返回值1
2
3
4
5
6fun transform(color: String): Int = when (color) {
"Red" -> 0
"Green" -> 1
"Blue" -> 2
else -> throw IllegalArgumentException("Invalid color param value")
}
try / catch表达式(‘try/catch’ expression)
Kotlin的try/catch表达式同Java类似,Kotlin可以直接赋值1
2
3
4
5
6
7
8
9fun test() {
val result = try {
count()
} catch (e: ArithmeticException) {
throw IllegalStateException(e)
}
// 处理result
}
方法使用Builder模式返回Unit(Builder-style usage of methods that return Unit)
1 | fun arrOfMinusOnes(size: Int): IntArray{ |
单表达式函数(Single-expression functions)
前面说过如果一个函数只有一个并且是表达式函数体并且是返回类型自动推断的话,可以直接等于返回值1
fun theAnswer() = 42
等同于1
2
3fun theAnswer(): Int {
return 42
}
使用with
调用一个对象实例的多个方法(Calling multiple methods on an object instance (‘with’))
1 | class Turtle { |
同样,在Adapter
里面可以直接使用with
来替换holder.itemView
1
2
3
4
5
6
7
with(holder.itemView) {
// 名称
new_item_text.text = mDatas?.get(position)?.desc
// 作者
new_item_user.text = mDatas?.get(position)?.who.let { Constant.NEW_ITEM_USER_NULL }
}
Java 7的try with resources
(Java 7’s try with resources)
try-with-resources
语句是一个声明一个或多个资源的 try
语句。一个资源作为一个对象,必须在程序结束之后随之关闭。
在Java 7 之前, 可以使用finally
块来确保资源被关闭,不管try
语句正常地完成或是发生意外。而try-with-resources
语句确保在语句的最后每个资源都被关闭 。1
2
3
4val stream = Files.newInputStream(Paths.get("/some/file.txt"))
stream.buffered().reader().use { reader ->
println(reader.readText())
}
泛型转换(Convenient form for a generic function that requires the generic type information)
1 | // public final class Gson { |
使用可空的Boolean
(Consuming a nullable Boolean)
添加?
符号可以让变量可为空1
2
3
4
5
6val b: Boolean? = ...
if (b == true) {
...
} else {
// `b` 是false或者为null
}
命名风格(Naming Style)
Kotlin的命名风格与Java的类似
- 使用骆驼命名法(在命名中避免下划线)
- 类型名称首字母大写
- 方法和属性首字母小写
- 缩进用四个空格
- ……
冒号(Colon)
在冒号之前有一个空格,冒号分隔类型和超类型(fun foo(a: Int): T
),没有空格,冒号分隔实例和类型(var bar: String
):1
2
3interface Foo<out T : Any> : Bar {
fun foo(a: Int): T
}
Lambdas
Kotlin支持Lambdas表达式,在 Lambdas 表达式中,大括号与表达式间要有空格,箭头与参数和函数体间要有空格。尽可能的把 Lambda 放在括号外面传入1
list.filter { it > 10 }.map { element -> element * 2 }
在短的且不嵌套的Lambdas中,建议使用it
替换参数,有嵌套而已有多个参数的Lambdas中,就不能用it
来替换参数,必须明确声明参数。