Kotlin vs NullPointerException

Kotlin is a language developed by the people at JetBrains back in 2011. It is mostly used as a language that compiles down to JVM bytecode, but it can also compile to JavaScript code. Kotlin was designed to be an enterprise level language which is better than Java. Since Kotlin is fully interoperable with Java, it enables developers and companies alike to gradually convert their codebase to Kotlin. Kotlin v1.0 was released on February 15, 2016. This is considered to be the first officially stable release and JetBrains has committed to long-term backwards compatibility starting with this version.

Android development with Kotlin

Kotlin was officially announced as a supported language for Android development at Google I/O 2017. I had heard of Kotlin before that, but I had never dabbled with it. This seemed like a great opportunity. Since Kotlin is fully interoperable with Java and it runs on the JVM, fans of this language used it for Android development evan before the I/O 2017, but Kotlin is now one of the officially supported Android development languages (if you don’t already know, Google officially supports C, C++ (NDK) , Java and Kotlin (SDK)).

Kotlin’s Null safety

One of the main features that make Kotlin “better than Java“, (according to the developers of the language), is the null safety. In Java, you can set a variable without initializing it. Like this:

Now is we print the length of the string s, we’ll get 15. But id we do something like this:

If we try to run this, we’ll get a message from the console that looks something like this:

Exception in thread "main" java.lang.NullPointerException
at NullSafety.main(NullSafety.java:13)

Now let’s try to do something similar in Kotlin.

Like Java, Kotlin does not allow this. Java throws a NullPointerException, but Kotlin won’t even compile.

Nullable types

The official Kotlin website provides a great comparison between Java nullables and Kotlin nullables. This is it:

And the same example in Kotlin:

Kotlin safe calls

Kotlin has a safe operator, and it is ?. This operator enables you to call methods which may result in returning a null.

b?.length

This statement will return the length if b, if it isn’t null, or it will return null.

The !! operator

The !! operator is used if you want to shoot yourself in the foot (Google I/O 2017. reference). This operator enables the NullPointerException. If the statement does not result in null, than it will return the non-null version of the result (for example a boolean), but if it does result in null, it will throw a NullPointerException

Reference