DEV Community

loading...

Android-Kotlin Digest #5 – Null Safety

itscoderslife profile image Coder Originally published at itscoderslife.wordpress.com on ・1 min read

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
Enter fullscreen mode Exit fullscreen mode
var str: String? = "abcd"
str = null // This pass thru since str is declared String?
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

And if developers are sure of an reference having a value then use not-null assertion operator ( !! )

val len = str!!.length
Enter fullscreen mode Exit fullscreen mode

(Problem with this is if the reference is null the NullPointerException is thrown)

happyCoding!

Discussion (0)

pic
Editor guide