Kotlin 处理 null 的方式
安全访问操作
val dialog : Dialog? = Dialog()
dialog?.dismiss() // if the dialog will be null,the dismiss call will be omitted
让函数
user?.let {
//Work with non-null user
handleNonNullUser(user)
}
提前退出
fun handleUser(user : User?) {
user ?: return //exit the function if user is null
//Now the compiler knows user is non-null
}
不可变阴影
var user : User? = null
fun handleUser() {
val user = user ?: return //Return if null, otherwise create immutable shadow
//Work with a local, non-null variable named user
}
默认值
fun getUserName(): String {
//If our nullable reference is not null, use it, otherwise use non-null value
return userName ?: "Anonymous"
}
使用 val 代替 var
val 是只读的,var 是可变的。建议尽可能多地使用只读属性,它们是线程安全的。
使用后期初始化
有时你不能使用不可变的属性。例如,当在onCreate() 调用中初始化某些属性时,它会在 Android 上发生。对于这些情况,Kotlin 有一个名为 lateinit 的语言功能。
private lateinit var mAdapter: RecyclerAdapter<Transaction>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mAdapter = RecyclerAdapter(R.layout.item_transaction)
}
fun updateTransactions() {
mAdapter.notifyDataSetChanged()
}