最好的方式来null检查kotlin?

我应该使用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

根据文档 ,优化你的代码没有意义,所以你可以使用a == nulla != 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") } 

检查有用的方法,这可能是有用的:

 /** * 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 }