Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Kotlin
Stage 5: Specialization

Part 03 / Stage 1

Null safety

Goal: Stop null pointer bugs at compile time instead of discovering them at 2 a.m. in production — use nullable types, ?., ?: and let by habit, understand lateinit and know exactly why !! has no place in code you write for this course. Time: ~4 hours · Level: comfortable with val/var and basic types (Part 2)

This is the part the course roadmap calls out by name: "the single habit that most separates idiomatic Kotlin from Java with different keywords." Every Java developer knows NullPointerException ("NPE"); almost none of them can tell you, just by reading a method signature, whether a given value is allowed to be null. Kotlin puts that answer directly into the type itself, and the compiler refuses to compile code that ignores it. That is the whole idea of this part, and everything below is one consequence of it or another.

What you will learn

  • Nullable types (String?) versus non-null types (String), and why the difference is checked by the compiler, not discovered at runtime
  • The safe call ?.: skip an operation instead of crashing when the value in front of it is null
  • The Elvis operator ?:: supply a default, or run a block (including throw or return), when the left-hand side is null
  • let combined with a safe call (?.let { ... }): run a block only when a value is actually present
  • !!, what it really does, and why this course does not use it even once
  • lateinit var versus a nullable type: two different answers to "I don't have this value yet"
  • Platform types (String!): an honest preview of what null safety looks like the moment Java code enters the picture (full Java interop arrives in Stage 2, Part 12)
  • Building it: a safe user-profile lookup for a small support-desk tool, with no !! anywhere

Topics in this part

Practice

Try each one yourself first. Then check the solution.

Every exercise is one file with a top-level fun main() — no custom classes yet (Part 7), no when/for/while yet (Part 4). Just val/var, maps, and the null-safety tools from this part: ?., ?:, ?.let { }, lateinit var, and deliberately, in two exercises, the mistakes this part warns against.


Exercise 1: Safe greeting for a cab app

Scenario: A ride-hailing app in Bengaluru greets riders by their preferred name, when one is on file. What to do: Given val preferredNames: Map<String, String> = mapOf("R1001" to "Kiran"), print a greeting for rider "R1001" using their real name, and a greeting for rider "R9999" (not in the map) that falls back to the word "rider" — using ?:, not an if.

Sample output:

Hello, Kiran! Your cab is 3 minutes away.
Hello, rider! Your cab is 3 minutes away.

💡 Hint: preferredNames[riderId] is already String?; ?: goes directly after it.


Exercise 2: Fix the broken program

Scenario: A teammate's program looks up a driver's name and shouts it in capitals. It does not compile.

fun main() {
    val drivers: Map<String, String> = mapOf("R1001" to "suresh kumar")
    val driverName: String? = drivers["R9999"]
    println(driverName.uppercase())
}

What to do: Fix it so it compiles, printing "NO DRIVER ASSIGNED" when the rider's driver isn't on file yet, and the driver's name in capitals when it is.

Sample output:

NO DRIVER ASSIGNED

💡 Hint: driverName is String?; .uppercase() needs ?., and the missing-driver case needs an ?: default — the same combination from section 3 of the README.


Exercise 3: Welcome SMS with let

Scenario: An order-tracking app texts customers when their order ships, but only the ones who gave a phone number. What to do: Given val phones: Map<String, String> = mapOf("ORD-501" to "98450 11223") and orders "ORD-501" and "ORD-502", send an SMS (just print "SMS to <number>: <text>") for each order that has a phone number on file, using ?.let { }, and print a skip message for any order that doesn't.

Sample output:

SMS to 98450 11223: Order ORD-501 is out for delivery
ORD-502: no phone on file, skipping SMS

💡 Hint: phone?.let { number -> sendSms(number, ...) } ?: println(...) reads like an if/else: the ?: branch only runs when the let branch never ran.


Exercise 4: lateinit quiz session

Scenario: A quiz app sets the current player's name the moment a game starts, and nothing should be able to read it before that. What to do: Declare lateinit var currentPlayer: String. Try to read and print it before calling a startGame(player: String) function that sets it, catching the real exception that results. Then call startGame("Ananya") and print it again, successfully this time.

Sample output:

caught: lateinit property currentPlayer has not been initialized
Game started for Ananya
Current player: Ananya

💡 Hint: The exception type is UninitializedPropertyAccessException, the same one section 6 of the README triggers on purpose.


Exercise 5: Reproduce and fix a !! crash

Scenario: Section 5 showed this happening to someone else's pincode lookup. Now make it happen to you, on a wallet balance, and fix it two different ways. What to do:

  1. Write a file with val balances: Map<String, Int> = mapOf("W-100" to 1500), look up "W-999" (not in the map), and print balance!! directly.
  2. Compile and run it, and copy the exact crash into a comment at the top of your solution file.
  3. Fix it two ways in the same file: first with an ?: default of 0, then with requireNotNull(...) { "..." } and a real message, each wrapped so the program keeps running and prints both results.

Sample output: (the broken version)

Exception in thread "main" java.lang.NullPointerException
    at Ex05_brokenKt.main(ex05_broken.kt:4)
    at Ex05_brokenKt.main(ex05_broken.kt)

Sample output: (the fixed version)

Balance (default): 0
requireNotNull threw: no wallet record for W-999

💡 Hint: The bare !! crash carries no message at all — that's the whole point of this exercise. requireNotNull is the one that finally says which wallet and why.


Exercise 6: Platform type trap

Scenario: Section 7 showed a platform type from System.getenv compiling cleanly, then crashing, when declared non-null. Reproduce that trap yourself with a different environment variable, then fix it. What to do:

  1. Write a file that declares val configPath: String = System.getenv("APP_CONFIG_PATH") (a variable that genuinely isn't set on this machine) and prints it.
  2. Compile and run it, and copy the exact crash into a comment at the top of your solution file.
  3. Fix it by declaring configPath as String? instead, and print a sensible fallback message when it's missing.

Sample output: (the broken version)

Exception in thread "main" java.lang.NullPointerException: getenv(...) must not be null
    at Ex06_brokenKt.main(ex06_broken.kt:2)
    at Ex06_brokenKt.main(ex06_broken.kt)

Sample output: (the fixed version)

Config path: using built-in defaults

💡 Hint: The broken version compiles with no warning at all — that's exactly what a platform type is. Nothing about the type checker catches this one; only choosing the honest declaration does.

Show the solutions for Part 3 (6 files)

solutions/ex01.kt

// Exercise 1: Safe greeting for a cab app
fun main() {
    val preferredNames: Map<String, String> = mapOf("R1001" to "Kiran")

    val riderId = "R1001"
    val greeting = "Hello, ${preferredNames[riderId] ?: "rider"}! Your cab is 3 minutes away."
    println(greeting)

    val unknownRiderId = "R9999"
    val fallbackGreeting = "Hello, ${preferredNames[unknownRiderId] ?: "rider"}! Your cab is 3 minutes away."
    println(fallbackGreeting)
}

solutions/ex02.kt

// Exercise 2: Fix the broken program
//
// Real transcript of the broken version (driverName.uppercase() with no ?.):
//
//   $ kotlinc ex02_broken.kt -d out
//   ex02_broken.kt:4:23: error: only safe (?.) or non-null asserted (!!.) calls are allowed
//   on a nullable receiver of type 'String?'.
//       println(driverName.uppercase())
//                         ^
//
// driverName is a String?, so a plain .uppercase() is rejected at compile time, before the
// program can ever run. Fixed below with ?. and a ?: fallback for the missing-driver case.
fun main() {
    val drivers: Map<String, String> = mapOf("R1001" to "suresh kumar")
    val driverName: String? = drivers["R9999"]
    println(driverName?.uppercase() ?: "NO DRIVER ASSIGNED")
}

solutions/ex03.kt

// Exercise 3: Welcome SMS with let
fun sendSms(number: String, text: String) {
    println("SMS to $number: $text")
}

fun main() {
    val phones: Map<String, String> = mapOf("ORD-501" to "98450 11223")
    val orders = listOf("ORD-501", "ORD-502")

    for (orderId in orders) {
        val phone: String? = phones[orderId]
        phone?.let { number -> sendSms(number, "Order $orderId is out for delivery") }
            ?: println("$orderId: no phone on file, skipping SMS")
    }
}

solutions/ex04.kt

// Exercise 4: lateinit quiz session
lateinit var currentPlayer: String

fun startGame(player: String) {
    currentPlayer = player
    println("Game started for $currentPlayer")
}

fun main() {
    try {
        println("Current player: $currentPlayer")   // reading before startGame()
    } catch (e: UninitializedPropertyAccessException) {
        println("caught: ${e.message}")
    }

    startGame("Ananya")
    println("Current player: $currentPlayer")
}

solutions/ex05.kt

// Exercise 5: Reproduce and fix a !! crash
//
// Real transcript of the broken version (balance!! on a missing wallet):
//
//   $ kotlinc ex05_broken.kt -include-runtime -d ex05b.jar
//   $ java -jar ex05b.jar
//   Exception in thread "main" java.lang.NullPointerException
//       at Ex05_brokenKt.main(ex05_broken.kt:4)
//       at Ex05_brokenKt.main(ex05_broken.kt)
//
// `!!` gives no clue which wallet was missing or why — just a bare NullPointerException.
// Fixed two ways below: an Elvis default, and a requireNotNull with a real message.
fun main() {
    val balances: Map<String, Int> = mapOf("W-100" to 1500)

    // Fix 1: a sensible default — a missing wallet simply has no balance to show, 0 works.
    val balanceOrZero: Int = balances["W-999"] ?: 0
    println("Balance (default): $balanceOrZero")

    // Fix 2: when 0 would be misleading and this really should never happen, fail loudly
    // with a message that says why, instead of a bare NPE.
    try {
        val confirmed = requireNotNull(balances["W-999"]) { "no wallet record for W-999" }
        println("Balance (confirmed): $confirmed")
    } catch (e: IllegalArgumentException) {
        println("requireNotNull threw: ${e.message}")
    }
}

solutions/ex06.kt

// Exercise 6: Platform type trap
//
// Real transcript of the broken version (APP_CONFIG_PATH declared as non-null String):
//
//   $ kotlinc ex06_broken.kt -include-runtime -d ex06b.jar
//   $ java -jar ex06b.jar
//   Exception in thread "main" java.lang.NullPointerException: getenv(...) must not be null
//       at Ex06_brokenKt.main(ex06_broken.kt:2)
//       at Ex06_brokenKt.main(ex06_broken.kt)
//
// It compiled without a single warning — a platform type (String!) lets you declare it
// however you like, right or wrong. The fix is to declare it the way it actually behaves.
fun main() {
    val configPath: String? = System.getenv("APP_CONFIG_PATH")   // the honest type: String?
    println("Config path: ${configPath ?: "using built-in defaults"}")
}

Common mistakes

Mistake Why it is wrong Fix
nickname.length where nickname: String? The compiler can't prove it isn't null at that point nickname?.length, or check if (nickname != null) first for a smart cast
city = null where city: String Only String? can ever hold null Declare it String? if null is really possible, or don't assign null at all
Reaching for !! to "make the error go away" Converts a compile-time warning into a runtime crash with no message ?: with a default, an early return, or requireNotNull(x) { "why" } if it should never happen
lateinit var count: Int lateinit doesn't work on primitive types (no "uninitialized" state exists for them on the JVM) Use a nullable Int? with a default, or give count a real initial value
lateinit val token: String lateinit only works on var Use var, or initialize the val immediately if you can
Using lateinit var for a value that might legitimately never exist It throws UninitializedPropertyAccessException on every read until something sets it — wrong model for "optional forever" Use a nullable type (String?) instead
Declaring a Java platform type (String!) as a non-null String just because it compiles Platform types carry no nullability guarantee; the compiler lets you declare it wrong Declare it String? and handle the null case, same as any other nullable
Checking if (x != null) then still writing x!!.foo() further down the same function Redundant, and defeats the smart cast the if already gave you for free Use x.foo() directly inside the if (x != null) branch

Quick recap

  • A type with ? (String?) can hold null; the same type without it (String) never can — and the compiler checks this at every use, not at runtime.
  • ?. skips a call when the receiver is null, instead of crashing; chain it freely.
  • ?: supplies a default, or runs a throw/return instead, when the left side is null.
  • ?.let { } runs a block only when there's a real value, with that value already smart-cast to non-null inside the block.
  • !! converts a nullable to non-null with a bare, message-less NullPointerException the moment it's wrong — this course never uses it; requireNotNull(x) { "why" } is the honest alternative when a crash really is the right outcome.
  • lateinit var is for "definitely set before anyone reads it, just not yet"; a nullable type is for "might genuinely never exist." They solve different problems and aren't interchangeable.
  • A platform type (String!) from Java code carries no nullability guarantee at all — treat it as nullable the moment it enters Kotlin, regardless of how you're tempted to declare it.

Checklist

  • I can explain, out loud, the difference between String and String? without looking it up.
  • I caused and read a real "only safe (?.) or non-null asserted (!!.) calls are allowed" compile error.
  • I wrote a chain of ?. calls and watched it return null instead of crashing.
  • I used ?: with both a plain default and a throw.
  • I used ?.let { } and can say why the value inside the block is non-null.
  • I deliberately triggered a !! NullPointerException, confirmed it carries no message at all, and rewrote it with requireNotNull and then with ?:.
  • I triggered and read a real UninitializedPropertyAccessException from an unset lateinit var.
  • I triggered a real NullPointerException from a Java platform type declared non-null, then fixed it by declaring it nullable.
  • I built the safe user-profile lookup myself, and confirmed it has no !! anywhere in it.

Search the guide