根据Kotlin docs,?运算符代表一个“安全调用”,这意味着如果它在方法调用链中使用,则整个链将返回null,如果它使用的任何值的值为null。
但如果它在作业的左侧使用了呢?因为左边不是“返回”的一面。看起来它可能有不同的效果。以下是我所谈论的一个例子:
val myObj = SomeObj()
myObj?.property = SomeClass.someFunc() // What does ?. do in this context?
答案 0 :(得分:28)
这意味着如果左侧的其中一个安全调用失败(即其接收方为空),则跳过整个赋值,并且根本不评估右侧的表达式。 / p>
val nullable: Container? = null
nullable?.x = f() // f is not called
答案 1 :(得分:2)
我看到了一个有趣的问题&刚刚在Kotlin回答。即使答案非常好,但我想更详细地澄清一下。
下面的作业表达式:
myObj?.property = SomeClass.someFunc()
Kolin将转换为Java字节码,如下所示:
val it = myObj;
if(it != null){
it.property = SomeClass.someFunc();
}
所以多线程没有问题。它仍然可以正常工作,我在github上进行了测试。但这会导致Thread Interference问题,这意味着当property
发生更改时,它会修改不同引用上的myObj
。
除了赋值表达式可以短路,其他人也可以短路。例如:
val array:Array<Any>? = null;
// v--- short-circuited
array?.set(0,SomeClass.someFunc());
// ^--- never be called