Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does ?. mean in Kotlin when used on the left side of an assignment?

Tags:

kotlin

According to the Kotlin docs, the ?. operator represents a 'safe call', meaning that if it's used in a chain of method calls, the entire chain will return null if the value of whatever it's used on is null.

But what about if it's used on the left side of an assignment? Since the left side isn't the side that's 'returning' anything it seems like it probably has a different effect. Here's an example of what I'm talking about:

val myObj = SomeObj()
myObj?.property = SomeClass.someFunc() // What does ?. do in this context?
like image 309
Sonofblip Avatar asked Jun 16 '17 13:06

Sonofblip


People also ask

What does :: mean in Kotlin?

:: is just a way to write a lambda expression basically we can use this to refer to a method i.e a member function or property for example class Person (val name: String, val age: Int) Now we can write this to access the person which has the maximium age.

What does question mark mean in Kotlin?

(Common source) (JVM source) (JS source) (Native source) true if this type was marked nullable in the source code. For Kotlin types, it means that null value is allowed to be represented by this type. In practice it means that the type was declared with a question mark at the end.

What does NULL safety mean in Kotlin?

Kotlin null safety is a procedure to eliminate the risk of null reference from the code. Kotlin compiler throws NullPointerException immediately if it found any null argument is passed without executing any other statements. Kotlin's type system is aimed to eliminate NullPointerException form the code.


2 Answers

It means that if one of the safe calls on the left-hand side fails (i.e. its receiver is null), then the whole assignment is skipped, and the expression on the right-hand side is not evaluated at all.

val nullable: Container? = null nullable?.x = f() // f is not called 

(runnable demo)

like image 94
hotkey Avatar answered Sep 27 '22 19:09

hotkey


I'm seeing a fun question & answer in Kotlin just now. Even if the answer is very nice, but I want to clarify it in more detailed.

The assignment expression below:

myObj?.property = SomeClass.someFunc() 

is transformed to Java bytecode by Kolin as below:

val it = myObj;

if(it != null){
   it.property = SomeClass.someFunc(); 
}

so there is no problem in multiple threads. It still works fine and I have tested it on github. But it will result in the Thread Interference problem, which means it will modify the property on different references when myObj is changed.

Except the assignment expression can be short-circuited, others also can be short-circuited. For example:

val array:Array<Any>? = null;

//   v--- short-circuited
array?.set(0,SomeClass.someFunc());
//                     ^--- never be called
like image 40
holi-java Avatar answered Sep 27 '22 19:09

holi-java