One of the most irritating things in programming is apps crashing due to null / nil objects.
In Objective-C, you can call a method on nil objects it wont crash but it will never ever give expected result and we developers end up debugging a whole lot of our time searching out for the culprit.
In Java it used to be NullPointerException (NPE). And reason for app crashes.
Modern languages solves this problem by having the null safety mechanisms.
Swift uses Optionals ? and Unwrapping ! the optionals. Swift also has if let and guard let statements for safely unwrapping the optionals and handle in case of nil values.
Here on the same lines we will discuss about how Kotlin ensures Null safety
var str: String = "abcd"
str = null // This line gives a compilation error
var str: String? = "abcd"
str = null // This pass thru since str is declared String?
Now suppose you want to check the length of str in case of optional, to do it safely you need to typically:
val len = if (str != null) str.length else -1
Or else use safe call operator ( ?. ) like : str?.length
(In swift we call it Optional chaining)
In Kotlin, the former if else statement can also written using what is called elvis operator ( *?: * )
val len = str?.length ?: -1
And if developers are sure of an reference having a value then use not-null assertion operator ( !! )
val len = str!!.length
(Problem with this is if the reference is null the NullPointerException is thrown)
happyCoding!
Top comments (0)