Safe calls(?.) vs Null checks(!!) in Kotlin

Suneet Agrawal
2 min readNov 13, 2017

--

In Kotlin, the type system distinguishes between references that can hold null (nullable references) and those that can not (non-null references).

This post was originally posted at https://agrawalsuneet.github.io/blogs/safe-calls-vs-null-checks-in-kotlin/ and reposted on Medium on 14th Nov 2017.

For example, a normal property can’t hold a null value and will show a compile error.

var variable : CustomClass = CustomClass()
variable = null //compilation error

Instead, we can add a ? after the data type of that property which declares that variable as a nullable property

var nullableVariable : CustomClass? = CustomClass()
nullableVariable = null //works fine

In any case, the nullable property requires a null check every time before utilizing that property or requires a confirmation from the developer that the estimation of that property won’t be null while utilizing it

variable.someMethodCall() //works fine as the compiler is sure that
//the variable can’t be null
nullableVariable.someMethodCall() //will highlight compilation error
//as compiler is not sure as
//nullVariable can be null.

There are still few techniques for using or accessing the nullable variable. One of them is safe call ?. and another one is null check !! but before figuring out the difference among both, let’s understand what they are in detail first.

Explicit Null Check
This is the old pattern that we use in every other language, checking the variable if its null or not.

if ( null != nullableVariable) {
nullableVariable.someMethodCall()
} else {
// fallback flow
}

Note this exclusive works where ‘nullableVariable’ is immutable (i.e. a local property which can’t be altered between the check and the utilization or a member ‘val’ which has a backing field and is not overridable), else it may happen that ‘nullableVariable’ changes to null after the check.
If it’s a mutable property, the explicit null check won’t work and the compiler will show the below compilation error.

Smart cast to ‘CustomClass’ is impossible, because ‘nullableVariable’ is a mutable property that could have been changed by this time.

Safe Calls (?.)
Another way of using a nullable property is safe call operator ?.
This calls the method if the property is not null or returns null if that property is null without throwing an NPE (null pointer exception).

nullableVariable?.someMethodCall()

Please continue reading at https://agrawalsuneet.github.io/blogs/safe-calls-vs-null-checks-in-kotlin/

That’s all for now. You can read my other interesting posts here or you can enjoy my games or apps listed here. Feel free to use my open-source Android components in your app listed here. Or drop an email, if you didn’t find what you are looking for and need some help.

Reference: Kotlin docs

--

--