
Some languages do not allow uninitialized values, such as Rust. You can use it in combination with the Elvis operator. So do Java, Scala, and Kotlin Ruby has nil etc. All right, It’s nice that Kotlin disallows method calls and property access on nullable variables to guard against NullPointerException errors. This enables the compiler to effectively prevent. Since Kotlin knows beforehand which variable can be null and which cannot, It can detect and disallow calls which could result in NullPointerException at compile-time itself. The reason behind this exception is that every object in Java.

Note that if the variable is a mutable property, you won't be able to smart cast it to its non-nullable type inside the if statement (because the value might have been modified by another thread) and you'd have to use the safe call operator with let instead. Null safety One of the best features of the Kotlin language is that it makes a clear distinction between nullable and non-null types. Null safety Probably the most notorious exception in the Java world is NullPointerException.

I’m not ditching the whole idea of using Kotlin’s null. Therefore when comparing to null, the structural equality a = null is translated to a referential equality a = null.Īccording to the docs, there is no point in optimizing your code, so you can use a = null and a != null We need to be careful in using Kotlin’s null safe calls, we can’t just use them just to get rid of the errors displayed in the IDE.

A structural equality a = b is translated to a?.equals(b) ?: (b = null)
