Skip to content

Beginner: Kotlin · Null safety, functions and lambdas · topic 5 of 50 · 30 min

Null safety

Explanation

In Kotlin a normal type like String can never hold null. If a value may be missing, its type says so with a question mark: String?. You then use the safe call ?. , the Elvis operator ?: for a default, smart casts after a null check, or let to run code only when the value exists. The !! operator forces a value and crashes if it is null, so avoid it.

The billion-dollar mistake

null means "no value here". In Java and many other languages, any object variable can secretly be null, and calling a method on it crashes the program with a NullPointerException (NPE). For years this was the most common crash in Android apps. Tony Hoare, who invented the null reference in 1965, later called it his "billion-dollar mistake".

Nullable and non-nullable types

Kotlin splits every type in two. String means "always a real string". String? (with a question mark) means "a string or null". The compiler tracks the difference and will not let you use a String? as if it were a String.

kotlin
fun main() {
    val name: String = "Asha"
    // val bad: String = null      // error: Null can not be a value of a non-null type String
    val nickname: String? = null   // fine: the ? allows null

    println(name.length)           // 4
    // println(nickname.length)    // error: only safe (?.) or non-null asserted (!!.) calls are allowed
}
The compiler forces you to deal with possible nulls before using them.

Safe call: ?.

The safe call operator ?. calls a method or reads a property only if the value is not null. If it is null, the whole expression simply becomes null instead of crashing.

kotlin
val nickname: String? = null
println(nickname?.length)          // null
val city: String? = "Mysuru"
println(city?.uppercase())         // MYSURU
Safe calls can be chained: user?.address?.pincode.

Elvis operator: ?:

The Elvis operator ?: gives a default value when the left side is null. (Turn it sideways and it looks like Elvis Presley's hair.)

kotlin
val nickname: String? = null
val shown = nickname ?: "Guest"
println("Hello, $shown")           // Hello, Guest

val len = nickname?.length ?: 0    // 0
Safe call plus Elvis is the most common null-handling pattern in Kotlin.

Smart casts after a check

kotlin
fun greet(name: String?) {
    if (name != null) {
        println(name.length)      // name is smart-cast to String here
    } else {
        println("No name")
    }
}
After name != null, the compiler knows name cannot be null inside that block.

let: run code only when not null

kotlin
val phone: String? = "9876543210"
phone?.let {
    println("Sending OTP to $it")   // runs only if phone is not null
}
Inside let, it is the non-null value.

The !! operator

!! (the not-null assertion) tells the compiler "trust me, this is not null". If you are wrong, the app crashes with a NullPointerException, exactly what null safety was meant to prevent. Use it almost never; prefer ?., ?: or an if check.

Careful: Calling Java code can still produce nulls the Kotlin compiler cannot see (called platform types). When a Java method might return null, store its result in a nullable type (String?) and handle it.
Think of it like this: A nullable type is like a parcel marked "may be empty". Before you use what is inside, you check. ?. is opening it only if something is there; ?: is "if empty, use this spare instead"; !! is tearing it open and assuming something is inside, and getting hurt if not.

Common mistakes

  • Sprinkling !! to silence errors. Each one is a possible crash.
  • Making every variable nullable "just in case". Use non-null types wherever a value must exist; nullability should mean something.
  • Forgetting that ?. returns a nullable result: nickname?.length is Int?, not Int. Add ?: to get a plain Int.
  • Trusting values from Java libraries or JSON to never be null.

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

Null safety · 1/7

NullPointerException

Null means no value. In many languages, using a null by mistake crashes the app.

Prefer a video by a teacher? Find free videos on “kotlin null safety safe call elvis operator tutorial” on YouTube ↗

In real life: An optional referral code at signup

A payments app lets new users enter a referral code, but most leave it empty. The code is stored as String?. When the signup is processed, the app uses referral?.trim()?.uppercase() to clean it only if it exists, and ?: "NONE" for reports. There is no way for an empty referral field to crash the signup.

kotlin
fun main() {
    val referral: String? = null
    val code = referral?.trim()?.uppercase() ?: "NONE"
    println("Referral: $code")    // Referral: NONE
}
Safe calls chain, and Elvis gives the default.

Practice (0/3 done)

Task 1 · Question

What does this print? val a: String? = null println(a?.length ?: -1)

Task 2 · Question

Which line does NOT compile?

Task 3 · Practice

Write fun formatPhone(input: String?): String that returns "Not given" for null or blank input, otherwise the trimmed number with "+91 " in front. Use ?. and ?: (and isNullOrBlank()). Test with null, " ", and " 9876543210 ".

Quick quiz

Question 1

1.What does the ? in Int? mean?

Question 2

2.What does x ?: 0 return when x is null?

Question 3

3.What happens with value!! when value is null?

Question 4

4.What is the type of name?.length when name is String??

Read more (free)

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

What does the ? in Int? mean?

Answer: The variable may hold null

A trailing ? marks a nullable type.

What does x ?: 0 return when x is null?

Answer: 0

Elvis returns the right side when the left is null.

What happens with value!! when value is null?

Answer: It throws a NullPointerException

!! asserts non-null and crashes if wrong.

What is the type of name?.length when name is String??

Answer: Int?

A safe call can produce null, so the result is nullable.

With nullable reference types enabled, what does string? mean?Related

Answer: A string that may be null

The ? marks that null is an allowed value.

From null, nullable types and null-safe operators

What is "sound" null safety?Related

Answer: If a type is non-nullable, the value can never be null at run time

The guarantee is enforced by the compiler.

From Sound null safety

Why is Option safer than null?Related

Answer: Only Option types can be missing, and the compiler makes you handle None

Absence is visible in the type and must be handled.

From Enums and Option

Which Kotlin feature should you avoid because it can throw a NullPointerException?Related

Answer: !!

!! asserts non-null.

From Interview questions: Kotlin

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. 3 more topics in “Null safety, functions and lambdas” before its exam: Functions, Lambdas and higher-order functions, Extension functions and scope functions.
  2. Module 2 exam: Null safety, functions and lambdas · 13 questions · 20 min, without help. 4 topics of this module still to finish first.
  3. Then the next module, Classes, objects and collections. 50 topics left in the course before the final exam.

← Previous: Loops and ranges