Kotlin使用总结
- Any所有类的基类
- object - 单例
- Kotlin的类默认不能继承,只有被open修饰的类能继承。继承类时,类后面要跟()
var & val & const
1
2
3var //读写
val //只读
const val //static finalcompanion object - static
1
2
3companion object {
private val TAG = "xxx"
}constructor & init
1
2
3class Xxx constructor(id:Int,name:String) {}
class Xxx(id:Int,name:String) {}
init {}字符串拼接
1
"${str1}连接符${it.value}"
with
1
2
3
4with (container.titles_panel) {
visibility = View.VISIBLE
title.text = data.title
}run, with, let, also, apply
if expression
1
val max = if (num1 > num2) num1 else num2
when取代java中的switch
1
2
3
4
5when(case) {
case1 -> xxx
case2,case3 -> xxx
else -> xxx
}elvis operator
1
return response.body()?.string() ?: "fail"
getOrPut - return value
1
xxxMap.getOrPut(key) { mutableSetOf() }
takeIf - T.takeIf return T
1
stripViewCache.takeIf { stripViewCache.size <= index }.add(xxxView())
mapOf
1
mapOf("key" to "value", "key" to "value")
Kotlin关键字
1
import org.mockito.Mockito.`when` as whenever
lazy
1
private val presenter by lazy { XxxPresenter(this) }