The Power of Kotlin’s Null safety.

Uchenna Chukwuwa
3 min readMar 14, 2020

Recently, I took a dive to study the new language everyone was singing about, and I had so much fun. The journey was amazing and I am officially in love again. Here is a little bit of the sweetest thing about the language Kotlin.

Now before I begin Let’s take a history lesson: Kotlin is a language that is 10 years old tho it’s official release was in February 2016 and it’s statically typed and targeted to run on the Java Virtual Machine which makes it a competitor to the language buff Java but that's just my opinion.

Now lets begin….

Kotlin is a Language that boasts of Null safety which is the menace that programming as a whole have been facing. By default Kotlin does not allow a variable to be declared as null but you can do so by adding a “?” after the type declaration.

In line one, we see the power of kotlin’s automatic type inference. By default, kotlin can infer types when the type is not explicitly stated.

In the second line we see the usual way of declaring variables by explicitly stating the type.

In the third line we see how to declare a variable as null in kotlin and we will see how kotlin deals with this type of variables.

when we try to call functions on nullable types the kotlin compiler throws an error because the variable is null, and if the code is allowed to run it can crash the system. So in kotlin, null is checked at compile time and not at run time which gives us the power to control and check for all the null values before running the code.

Safe call(?)

There are ways to let kotlin allow null values to run. The first way is by using the safe call. This call allows the function called on a nullable type, to run only if it’s not null, if it’s null the function is not called . This reduces the amount of if statements to check for nulls in our code making it possible to write concise codes.

As we see in the code snippet above the variable name2 is a nullable type and calling the length() method will throw a compile time error. Alternatively the safe call operator will enable this code run smoothly even when the variable is null.

Elvis operator(?:)

An Elvis operator is used for conditional assignment when the variable in question is null.

The operator checks if the variable is null and then assigns it a value if it's null. In this case it checks if name2 is null, and if it is, it assigns "Bob" to it.

Not-Null assertions(!!)

This is a very interesting operator and if used wrongly can make Kotlin code behave like Java code when it comes to handling nullability. It should be used only when you are sure the variable will not be null.

And with this we see how kotlin gives us null safety.

--

--

Uchenna Chukwuwa

Android Developer || Tech Enthusiast || Speaker || Mentor || Mentee