You never touched Groovy, nor did you jump on the Scala train. Clojure never attracted you; and you heard about Ceylon long after the language had already died. You are one of those old-fashioned Java folks! But now, after all those years, you want to join the cool Kotlin kids. So, where to start? Let’s discover the language together by decompiling it to Java code. Today: Null Safety and the Safe Call Operator!

Today: Null Safety and the Safe Call Operator

Kotlin is one of those languages with built-in null safety. This means the type you define is just that. If you look at null unsafe languages like Java, any defined type can exist or not exist by being null. In Kotlin this is not the case, a type cannot be null by default. But you can change this default by using the ? operator to mark the type as nullable[1]:

data class Person(val name: String?)
data class Department(val name: String, val head: Person?)

As we discovered earlier, the @NotNull annotation is added automatically when you use a type in a class. Now the compiler also creates the @Nullable annotation for nullable types:

public final class Department {
   @NotNull
   private final String name;
   @Nullable
   private final Person head;

   // rest
}

Sweet. But as said before, Kotlin has build-in support for nullable types. This goes a lot further than just being a language where the type system prevents null pointer exceptions. The language provides a safe call ?. and elvis ?: operator to write the code a lot shorter:

val securityDepartment = Department("Security", null /* no head person */)
val head: String? = securityDepartment.head?.name
val headOrDefault: String = securityDepartment.head?.name ?: "Bob"

The safe call operator is just syntactic sugar to avoid having to write all those pesky null checks yourself. The elvis operator returns its value if the expression on the left returns null[2]:

Department securityDepartment = new Department("Security", (Person)null);
Person person = securityDepartment.getHead();
String head = person != null ? person.getName() : null;
String headOrDefault = person != null && person.getName() != null ? person.getName : "Bob";

But that’s not all. The Kotlin API provides a lot of nice functions to work with nullable objects natively. Most of them are called isNullOrThat or thatOrNull:

val nullableString: String? = null
val nullableList: List<String> = listOf()

val x = nullableString.isNullOrBlank() // x == true
val y = nullableList.firstOrNull() // y == null

So don’t forget to check those out as well! Well, that’s enough for one day. Stay tuned for more!


1. If you are familiar with union types, think of a nullable type as a type being defined as: T | null.
2. This time the compiler really made an ugly mess with lots of if statements and a label. For clarity’s sake I rewrote the Java code myself.
shadow-left