Kotlin's type system is aimed at eliminating the danger of null references, also known as The Billion Dollar Mistake.
One of the most common pitfalls in many programming languages, including Java, is that accessing a member of a null reference will result in a null reference exception. In Java this would be the equivalent of a NullPointerException, or an NPE for short.
few possible causes of an NPE in Kotlin are:
An explicit call to throw NullPointerException().
Usage of the !! operator that is described below.
Now, if you call a method or access a property on a, it's guaranteed not to cause an NPE, so you can safely say:
val l = a.length
But if you want to access the same property on b, that would not be safe, and the compiler reports an error:
val l = b.length // error: variable 'b' can be null
this will work as compiler knows:
val l = if (b != null) b.length else -1
let() method –
To execute an action only when a reference holds a non-nullable value, we can use a let operator. The lambda expression present inside the let is executed only if the variable firstName is not null.