我應該使用雙重=
還是三重=
?null check in kotlin的最佳方法是什麼?
if(a === null) {
//do something
}
或
if(a == null) {
//do something
}
同樣,對於 '不等於':
if(a !== null) {
//do something
}
或
if(a != null) {
//do something
}
我應該使用雙重=
還是三重=
?null check in kotlin的最佳方法是什麼?
if(a === null) {
//do something
}
或
if(a == null) {
//do something
}
同樣,對於 '不等於':
if(a !== null) {
//do something
}
或
if(a != null) {
//do something
}
這兩種方法都產生相同的字節碼,使你可以選擇任何你喜歡的。
如果我理解正確,那麼他會要求檢查Kotlin中的null,而不是使用哪種方法生成最佳字節碼。@ BenitoBertoli答案看起來很有希望,它減少了樣板代碼 – imGs
甲結構相等a == b
被轉換爲
a?.equals(b) ?: (b === null)
因此比較null
時,結構平等a == null
被轉換到參照平等a === null
。
按照docs,還有優化你的代碼是沒有意義的,所以你可以使用a == null
和a != null
注意,如果變量是一個可變的特性,你將不能夠智能將它轉換爲if
語句中的非空類型(因爲該值可能已被另一個線程修改),您必須改用安全調用運算符let
。
安全調用操作?.
a?.let {
// not null do something
println(it)
println("not null")
}
可以結合貓王運營商使用它。
貓王運營商?:
(我猜是因爲問號看起來像貓王的頭髮)
a ?: println("null")
如果你想運行的代碼
a ?: run {
println("null")
println("The King has left the building")
}
塊結合兩者
a?.let {
println("not null")
println("Wop-bop-a-loom-a-boom-bam-boom")
} ?: run {
println("null")
println("When things go null, don't go with them")
}
爲什麼不使用如果爲空檢查? 'a?.let {}?:run {}'只適用於極少數情況,否則它不是慣用的 – voddan
@voddan我並不是建議不用'if'檢查,我列出了其他可行的選項。儘管我不確定'跑'是否會帶來某種性能損失。我會更新我的答案,使其更清楚。 –
檢查有用的方法了,它可能是有用的:
/**
* Performs [R] when [T] is not null. Block [R] will have context of [T]
*/
inline fun <T : Any, R> ifNotNull(input: T?, callback: (T) -> R): R? {
return input?.let(callback)
}
/**
* Checking if [T] is not `null` and if its function completes or satisfies to some condition.
*/
inline fun <T: Any> T?.isNotNullAndSatisfies(check: T.() -> Boolean?): Boolean{
return ifNotNull(this) { it.run(check) } ?: false
}
下面是可能的例子,如何使用這些功能:
var s: String? = null
// ...
if (s.isNotNullAndSatisfies{ isEmpty() }{
// do something
}
有旁觀鏈接: - https://kotlinlang.org /docs/reference/null-safety.html ..............在Kotlin Docs中很容易 – sushildlh