1. 安全運算符 ?. 與Elvis運算符 ?: 配合使用
nimAccount = teacher?.nim()?.accid() ?: "jake"
nimToken = teacher?.nim()?.token() ?: "test"
上述代碼 等價于 如下代碼 :
if (teacher != null && teacher.nim() != null && teacher.nim()!!.accid() != null) {
nimAccount = teacher.nim()!!.accid()
} else {
nimAccount = "jake"
}
if (teacher != null && teacher.nim() != null && teacher.nim()!!.token() != null) {
nimToken = teacher.nim()!!.token()
} else {
nimToken = "test"
}
安全運算符 ?.
s?.toUpdate() <=兩者等價=> if (s!=null) s?.toUpdate() else null
Elvis運算符 ?: 請看這篇文章
兩者結(jié)合,功能強(qiáng)大。
2. 安全運算符 ?. 與 let函數(shù) 配合使用
nimAccount?.let {
registerMsgRevokeFilter(it)
// 注冊撤回觀察者
registerMsgRevokeObserver()
}
上述代碼等價于
if (nimAccount!=null){
registerMsgRevokeFilter(nimAccount!!)
// 注冊撤回觀察者
registerMsgRevokeObserver()
}
你可能覺得使用 let函數(shù) 并沒有方便多少,
但這兩種方式都可以實現(xiàn) 將可空類型的參數(shù)傳遞給非空函數(shù)
let函數(shù)
功能:把一個調(diào)用它的對象變成lambda表達(dá)式,常結(jié)合安全運算符使用。
安全調(diào)用"let"只在表達(dá)式不為null時,執(zhí)行l(wèi)ambda
使用let函數(shù),可以使代碼更優(yōu)雅~