Kotlin Safe call operator


To access functions and properties of nullable types, you have to use special operators.

The first one, ?., gives you the property or function you're trying to access, or it gives you null if the object is null:

val string: String? = "Hello World!"
print(string.length)   // Compile error: Can't directly access property of nullable type.
print(string?.length)  // Will print the string's length, or "null" if the string is null.

Idiom: calling multiple methods on the same, null-checked object

An elegant way to call multiple methods of a null-checked object is using Kotlin's apply like this:

obj?.apply { 

This will call foo and bar on obj (which is this in the apply block) only if obj is non-null, skipping the entire block otherwise.

To bring a nullable variable into scope as a non-nullable reference without making it the implicit receiver of function and property calls, you can use let instead of apply:

nullable?.let { notnull ->

notnull could be named anything, or even left out and used through the implicit lambda parameter it.