1. Overview

Kotlin is a null-safe programming language, in the sense that it differentiates between nullable and non-nullable data types.

In this quick tutorial, we’re going to see what happens when we store a null value into a non-null data type in Kotlin.

2. Storing null Values in Non-Nullable Types

The Kotlin compiler will enforce the null-safety of data types at compile-time. So if we write something like:

val name: String = null

Then, the compiler will complain with an error at compile-time:

Kotlin: Null can not be a value of a non-null type String

Even though the Kotlin compiler enforces null-safety at compile-time, sometimes we may need another safety measure at runtime, too. Put simply, sometimes storing a null value into a non-nullable variable isn’t apparent at compile-time. So the compiler needs the runtime help in these cases.

To make matters more concrete, let’s consider a simple data model class:

data class User(val id: Long, val username: String)

If we try to set the username field to null via reflection:

val constructor = User::class.java.constructors[0]
val createInstance = { constructor.newInstance(42L, null) }

Then Kotlin will throw an exception since the username field is set to null:

val exception = assertThrows { createInstance() }
 assertThat(exception.cause).isInstanceOf(NullPointerException::class.java)
 assertThat(exception.cause?.message).startsWith("Parameter specified as non-null is null")

If we don’t assert the exception details, the runtime will print the following stack trace:

java.lang.NullPointerException: Parameter specified as non-null is null: method User.<init>, parameter username
// truncated

The stack trace is obvious: A non-null property named username from the User class constructor (<init> is the constructor) is set to null. Before Kotlin 1.4, however, the same error manifested itself as an IllegalArgumentException.

The bottom line is that Kotlin throws this exception with this particular message pattern when we set a non-null property to null at runtime.

3. Conclusion

In this short tutorial, we learned how Kotlin enforces null-safety at both compile-time and runtime.

As usual, all the examples are available over on GitHub.

Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.