Kotlin null safety explained

In my Java developer’s career, NullPointerException is the single most common runtime error I encounter. And according to this research, I’m not an exception (pun intended!). Even the inventor of null reference, computer science pioneer Tony Hoare called it The Billion Dollar Mistake.

Fortunately, Kotlin introduces the concept of null safety. If you are using pure Kotlin (without mixing it with Java code) you encounter two types of references:

  1. The Non-Null type:
var nonNullReference: String = "I can't be null!"
nonNullReference = null // Compile-time error

The non-null string’s type is written as 'String'

  1. The Nullable type:
var nullableReference: String? = "I'm a nullable string"
nullableReference = null // Compiles just fine

The nullable string’s type is written as 'String?', with question mark suffix

This way we’re sure that the non-null reference will never throw dreaded NullPointerException. But what happens if we try to call some function on the nullable reference? It won’t happen because it will not compile. The compiler doesn’t care if the reference is null or not:

println(nullableReference.length) // Compile-time error

We can’t call functions on nullable references without explicitly handling the nullability. There are 3 basic ways to do that:

  1. “Classic” null check:
if (nullableReference != null) {
    println(nullableReference.length)
    println(nullableReference.hashCode())
    println(nullableReference.capitalize())
}

This is the exact same way as every Java coder did thousands of times. Compiler knows all the uses of our nullableReference inside the if block are safe, cause we checked it’s not null before the calls are being made.

  1. Safe call:
println(nullableReference?.length)

The Kotlin safe calls are being made using the special operator '?.' - in our case, the expression println(nullableReference?.length) will not crash at runtime but instead return null. If the nullableReference wasn’t null it would return the string’s length as 'Int?' (which itself is a nullable integer).

  1. Non-null asserted call:
println(nullableReference!!.length) // NPE thrown at runtime

While using a double exclamation mark (a.k.a “double bang”) we are stating that we’re 100% sure our nullableReference is not null. This is the same behaviour as classic Java call without doing null-check. In our case, the app will crash and the NullPointerException will be thrown! This notation was made ugly on purpose, it is basically an indicator of code smell and should be used only when you want your app crash at runtime whenever there’s null reference. In most cases you should either:

  • Use non-nullable types whenever possible or
  • If you are using nullable type, do a safe call or a null-check

But what if we are mixing Kotlin with Java?

Fortunately, when our Java code is properly annotated it will behave exactly the same as Kotlin code. Kotlin compiler recognizes many popular annotation frameworks, including Android annotations framework. If developer properly annotates the code with '@NotNull' and '@Nullable' annotations, the compiler will see those references as if they were Kotlin types. Fortunately for us mobile developers, Android framework and many popular libraries are already annotated properly.

If for whatever reason the Java code you are using wasn’t annotated, Kotlin introduces the concept of platform types. This means that whenever you are using such code, it will be treated the same as in Java. This was done for convenience (so the code wouldn’t be filled with question marks and double-bangs). The platform type string is marked as 'String!'.

10 reasons why Kotlin will be big

In this post, I’m going to list 10 reasons why in my opinion Kotlin will become a popular programming language. Keep in mind those are my personal views.

  1. The main reason: Java programming language appeared 22 years ago which makes it quite an old technology. Java was improved upon a lot since 1995 but had to maintain most of its core features and syntax. The code written in Java is famous for not being very readable and maintainable. I’m not going to elaborate here, it would require a separate post to list all the issues with Java as a programming language in 2017.

  2. Kotlin is extremely easy to learn for an experienced Java developer. Basically, Kotlin could be called “Java 2.0 without the syntax compatibility”. I’m not the best Java developer out there nor the most experienced, but it took me around 5 days of playing with Kotlin (in the evenings, for about 2-3 hours each session) to be able to write production Kotlin code that was on pair with my Java code in terms of quality. There are a lot of new features and concepts (especially if you come from Java < 1.7-1.8) but you can learn them gradually. Kotlin doesn’t have a steep learning curve similar to Scala. If you’re a decent Java or C# coder you will be able to grasp it really quickly.

  3. Kotlin is developed by very competent people with a lot of support behind them. Four weeks ago at Google I/O 2017 Android Development Tools team announced official Kotlin support for Android. It is well proven that Open Source projects (especially programming languages) have greater success rate with support from big commercial organizations.

  4. One of the main design principles behind Kotlin is Java interoperability. I can tell from my own personal experience that this is not just some marketing BS. It really works well with Java! And by “Java interoperability” guys at JetBrains mean mixing Java and Kotlin in your codebase as well as using Java libraries in your 100% Kotlin app (my experience here is limited to Android development but I have no reasons to doubt it will behave the same in some more “classic” Java uses).

  5. Android OS is HUGE! Right now there are around 2 billion Google Android devices in the wild. Add around 500 to 700 million devices without “Google Experience” package and it is by far most popular computer OS in history. And it will be more popular - install base will probably double by the end of 2021. Google is also developing other platforms based on Android OS, most notable Android Things. And Android development needs a modern programming language. Kotlin is an obvious choice here.

  6. Kotlin is being designed to be ubiquitous and universal. Right now it compiles to Java bytecode and can run on any JVM which supports Java 1.6 or later. It also compiles to JavaScript. Kotlin team is also working with LLVM on Kotlin/Native. All those efforts might in the future result in something that might be called “semi-universal computer language”, meaning it could be used in most development tasks (frontend, backend, high and low-level development).

  7. Kotlin is modern computer language which has all the “cool” features needed in 2017. Java <1.8 is not. Simple as that.

  8. Kotlin is designed with safety as its core principle (similar to Swift). Some people don’t like languages designed to shelter programmers from their own stupidity, but I personally am a big fan of such solutions. We are imperfect people and operate in the imperfect world (limited resources, deadlines, unskilled developers on our teams) and this kind of tradeoff in most cases is an advantage.

  9. Kotlin was designed by a commercial entity with a goal of being an industrial language used for real-life applications. This might sound like something that is a marketing jibberish, but IMO, some of the languages designed by academics have a little bit different DNA and aren’t that suitable for real world applications as Kotlin.

  10. Kotlin is FAR MORE readable than Java code. There are multiple reasons for that - its syntax is more concise, there is a lot of syntactic sugar built in (i.e. Data objects). In my personal experience, when I refactor my Android code using Kotlin I end up trimming around 20 to 40% of my code “volume”, without resolving to any nasty one-liners or ugly hacks.

To sum it all up, there are computer languages which have some of those advantages, but so far there was no single language which combined them all. The rapid and wide Kotlin adoption only proves my thesis - Kotlin WILL be big!

First post - Hello World!

Hi! This is first test post on this blog!

Testing embedded YouTube video:

Code

This is just a sample of some Kotlin code snippet.

// Standard onClickListener

view.setOnClickListener(object : View.OnClickListener {
    override fun onClick(v: View?) {
        toast("Hello World!")
    }
})

// Proper "Kotlinish" onClickListener (with Anko)

view.setOnClickListener { toast("Hello World!") }

More to come…