double=
または tripleを使用する必要があります=
か?
if(a === null) {
//do something
}
また
if(a == null) {
//do something
}
同様に「等しくない」の場合:
if(a !== null) {
//do something
}
また
if(a != null) {
//do something
}
double=
または tripleを使用する必要があります=
か?
if(a === null) {
//do something
}
また
if(a == null) {
//do something
}
同様に「等しくない」の場合:
if(a !== null) {
//do something
}
また
if(a != null) {
//do something
}
構造的等価性a == b
は次のように変換されます
a?.equals(b) ?: (b === null)
したがって、 と比較するnull
と、構造上の同等性a == null
は参照上の同等性に変換されa === null
ます。
docsによると、コードを最適化しても意味がないため、変数を使用して、変数が変更可能なプロパティである場合、ステートメント内で null 非許容型にスマート キャストできないことa == null
にa != null
注意if
してください (値は別のスレッドによって変更された可能性があります)、let
代わりに安全な呼び出し演算子を使用する必要があります。
安全な通話オペレーター ?.
a?.let {
// not null do something
println(it)
println("not null")
}
Elvis オペレーターと組み合わせて使用できます。
エルヴィスのオペレーター?:
(尋問マークがエルヴィスの髪の毛に似ているので推測)
a ?: println("null")
そして、コードのブロックを実行したい場合
a ?: run {
println("null")
println("The King has left the building")
}
2つを組み合わせる
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")
}
どちらのアプローチでも同じバイトコードが生成されるため、好きなものを選択できます。
便利なメソッドをチェックしてください。役に立つかもしれません:
/**
* 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
}