Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 134 ยท Control Flow

Null Safety

Learn Kotlin null safety - nullable types, safe calls, the Elvis operator, !!, let, smart casts, safe casts, lateinit and platform types, with runnable examples and the real compiler errors.

In 1965 Tony Hoare invented the null reference, and later called it his "billion-dollar mistake". In many languages any object variable can secretly be null, and using it crashes the program with a NullPointerException (NPE) at run time, often far away from the code that caused the problem. Kotlin's answer is to move the problem from run time to compile time. In Kotlin, the type tells you whether null is possible, and the compiler refuses code that could dereference a null.

This is one of the main reasons teams choose Kotlin, and it changes how you write every function. In this lesson you will learn the two kinds of types, the operators for working with nullable values (?., ?:, !!), the tools that make the compiler smarter (let, smart casts, as?), and how Kotlin treats values that come from Java.

Nullable and non-null types

Every type T in Kotlin comes in two flavors: T (never null) and T? (null allowed). A String always holds a string. A String? holds a string or null.

Kotlin Assigning null (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The compiler stops with main.kt:3:12: error: null cannot be a value of a non-null type 'String'. There is nothing to catch at run time because the program never starts. Make the type nullable and it compiles:

Kotlin A nullable variable

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

You can compare with null using == and != like any value. Printing a null with println shows the text null.

Now the key rule: you cannot use a nullable value as if it were non-null. Calling a method on a String? could fail, so the compiler forbids it:

Kotlin Calling a method on a nullable (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Here the compiler reports: main.kt:3:17: error: only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type 'String?'. The message already names the two tools you have, and the rest of this lesson is about choosing between them (and better ones).

Safe calls: ?.

The safe call ?. calls a member only if the receiver is not null. If it is null, the whole expression is null and nothing is called.

Kotlin Safe calls

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Look at the return type: Int?. The result of a safe call is always nullable, because it might be the "receiver was null" case. Safe calls chain: in city?.trim()?.lowercase()?.length, the moment one link is null the whole chain becomes null and the rest is skipped without error. This replaces a pyramid of if (x != null) { if (x.y != null) ... } checks with one line.

Safe calls also work for assignment: user?.name = "Bo" assigns only when user is not null.

The Elvis operator: ?:

Eventually you need a real value instead of a maybe. The Elvis operator ?: (turn your head sideways to see Elvis's hair) says: use the left side if it is not null, otherwise the right side.

Kotlin Default values with ?:

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The right side can be any expression, including return, break, continue or throw, because these have the type Nothing (see Any, Unit and Nothing). That makes "validate and leave early" read well:

Kotlin ?: with return and throw

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

After val map = user ?: return "no user", the variable map has the non-null type Map<String, String>. The null case has been dealt with, and the compiler knows it.

The not-null assertion: !!

x!! means "I promise x is not null; throw if I am wrong". It converts T? to T, and throws a NullPointerException if the value is null.

Kotlin !! throws (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The program prints about to assert, then ends with Exception in thread "main" java.lang.NullPointerException. You have rebuilt the Java problem by hand. Treat !! as a smell: every use is a place where you told the compiler to stop helping you. It is acceptable in tests, in prototypes, and in the rare case where a fact is guaranteed by something the compiler cannot see, in which case a comment explaining why is good practice. In production code prefer ?: with a meaningful fallback or error, or requireNotNull(x) { "message" }, which throws IllegalArgumentException with your message instead of an anonymous NPE.

Smart casts after null checks

If you check for null yourself, the compiler remembers the result and smart casts the variable to its non-null type inside the checked branch:

Kotlin Smart cast after a null check

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Smart casts only apply when the compiler can prove that the value cannot change between the check and the use. That works for local vals, for vars that are not captured and modified by a lambda, and for val properties without custom getters in the same module. It does not work for a mutable var property, because another thread or function could set it to null in between:

Kotlin No smart cast on a mutable property (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The compiler reports main.kt:9:17: error: smart cast to 'String' is impossible, because 'nickname' is a mutable property that could be mutated concurrently. The fixes: copy the property into a local val (val nick = profile.nickname), or use profile.nickname?.length, or let. The copy is the most common and also gives you a consistent snapshot.

let: do something only when not null

let is a scope function (more in Scope Functions) that runs a block with the value as it. Combined with ?., it means "if this is not null, do that":

Kotlin ?.let

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Inside the block, it is non-null. email?.let { ... } is the idiom for a statement; for a simple if whose body is one line, if (email != null) is just as readable. Do not nest lets five levels deep; at that point flatten the logic with early returns and ?:.

Notice filterNotNull() too: a List<Int?> becomes a List<Int> by dropping the nulls. Nullability is part of generic types, so List<Int?> (the elements may be null) and List<Int>? (the list itself may be null) mean different things.

Safe casts: as?

A normal cast x as String throws ClassCastException if x is something else. The safe cast as? returns null instead, which fits perfectly with ?::

Kotlin as? returns null on failure

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Casting is covered in full in Type Checks and Casts.

lateinit and platform types

Sometimes a property cannot be set in the constructor, but you also do not want a nullable type that forces ?. everywhere, for example a value injected by a framework or set up in a test. Mark it lateinit var. Reading it before assignment throws an exception that says exactly what is wrong:

Kotlin lateinit read too early (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The first three lines work (ready: false, ready: true, then the address); the last call ends with kotlin.UninitializedPropertyAccessException: lateinit property endpoint has not been initialized. Note that isInitialized can only be asked from inside the class that declares the property. lateinit is for vars with non-null, non-primitive types. It trades compile-time safety for convenience, so use it sparingly (details in Advanced Properties).

Platform types: null safety at the Java border

Kotlin code calls Java all the time, and Java has no String? versus String. A Java method that returns String may return null, and Kotlin cannot know. So Kotlin gives such values a special platform type, written String! in IDEs and error messages: the compiler lets you treat it as either String or String?, and the check happens at run time.

Kotlin A platform type from Java (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The first two lines print null twice. The third assignment ends with an exception, which names the expression that produced the unexpected null (System.getProperty(...) must not be null) as soon as the value is assigned to a non-null type. The rule of thumb: when you receive a value from Java, declare the type yourself, and declare it nullable if there is any doubt. The lesson on Java Interoperability shows how nullability annotations improve this.

Practical rules

  • Make types non-null by default and nullable only when absence is a real, meaningful state ("no middle name"), not as a lazy placeholder.
  • Handle the null once, near the edge of your program, and pass non-null values inward. A deep call chain full of String? means the decision was not made early enough.
  • Prefer ?: with an explicit default or error over !!.
  • Functions that may fail to produce a value can return T?: toIntOrNull(), firstOrNull(), getOrNull(). The ...OrNull naming convention tells callers what to expect, and the non-OrNull versions throw.
  • For collections, prefer an empty collection to a null one. Callers then loop without any check.

Null safety protects against the NPE for Kotlin-only code. It cannot protect against nulls that sneak in from Java libraries, reflection or deserialization frameworks that bypass constructors. The platform-type section above is where these leaks begin.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the type of the expression name?.length when name is a String?

    A safe call yields null when the receiver is null, so its result type is nullable: Int?.
  2. 2. What does val port = config.port ?: 8080 do if config.port is null?

    The Elvis operator evaluates to its left side if that is not null, otherwise to its right side, here 8080.
  3. 3. Why does if (obj.name != null) println(obj.name.length) fail to compile when name is a var property?

    A mutable property may be modified between the check and its use (even by another thread), so the compiler refuses the smart cast. Copy it into a local val first.
  4. 4. What is the main risk of the !! operator?

    !! tells the compiler to trust you; if the value is null, the program throws a NullPointerException. Prefer ?: or requireNotNull with a message.
  5. 5. What is a platform type such as String!?

    Java declarations carry no nullability information, so Kotlin lets you treat the value either way and checks when you use it as non-null. Declare the type yourself when you can.

Summary

  • T can never be null; T? may be. The compiler refuses to use a T? as a T.
  • ?. calls a member only on non-null receivers and yields a nullable result; chains short-circuit.
  • ?: provides a default, or return, throw, break, continue when the left side is null.
  • !! asserts non-null and throws a NullPointerException otherwise; avoid it in production code, and use requireNotNull when you need a clear message.
  • After a null check, smart casts give you the non-null type, but not for mutable properties: copy to a local val.
  • let, as?, filterNotNull() and the ...OrNull functions are the everyday companions.
  • Values coming from Java have platform types: declare your own type and make it nullable when unsure.

Next: Type Checks and Casts