Null Safety: The Type System's Guard Rail

Null Safety: The Type System's Guard Rail in Kotlin: --- The stores counter at an engineering works issues parts against written cards, and the cards come in…


The Analogy: The Stores Counter and the Pink Requisition Card

The stores counter at an engineering works issues parts against written cards, and the cards come in two colours. A white card is raised only for items the storeman has confirmed are physically on the shelf: it carries the part number, the bin, and a quantity, and the fitter who takes it to the machine shop knows that walking to bin A1 will produce the part. A pink card is raised for everything else -- items that may be on the shelf, may be on order, may have been written off in last year's stocktake. Both cards are the same size, both go in the same wire tray, and both are filled in with the same pencil. The only difference is the colour of the stock they are printed on, and that colour is chosen at the moment the card is raised.

The colour is the type. In Kotlin, String is the white card and String? is the pink one, and the decision is made in the declaration rather than at the counter. A function that takes a String is a machine shop that accepts white cards only; hand it a pink card and the storeman stops you at the hatch, which is to say the code does not compile. This is not a runtime check, and no part of it costs anything when the program runs. It is a paperwork rule enforced before the paperwork leaves the office.

The counter has four ways of dealing with a pink card, and Kotlin gives each one an operator. The storeman can walk to the shelf and come back either with the part or with nothing, reporting whichever happened -- that is the safe call, ?., which produces a result or produces null and never throws. He can substitute an agreed alternative when the shelf is empty, which is the elvis operator, ?:. He can hold the card up to the hatch light, confirm there is a part behind it, and from that moment treat it as white for the rest of the conversation -- that is a null check plus a smart cast. Or he can sign the override box, certifying on his own authority that the part is there, which is !!.

The failure mode is the override box, and it is always the same story. A storeman under pressure signs the override without walking to the shelf, because the part was there this morning and there is a queue behind the fitter. The card goes through as white, the machine shop plans around a part that does not exist, and the line stops two hours later at the point of assembly rather than at the counter where the lie was told. In Kotlin that is !! throwing a NullPointerException deep inside a call chain, with a stack trace that names the assembly bay and says nothing about who signed the card. The whole apparatus exists so failures surface at the hatch, and every !! is a deliberate decision to move one back to the assembly bay.


Syntax or Core Structure

A nullable type is written with a trailing question mark, and every one of the counter's four moves has a symbol. The lookup below returns String? because a code that is not on the shelf list has no answer, which is the ordinary way nullability enters a Kotlin program: not from a variable someone set to null, but from a query that can legitimately find nothing.

fun shelfLookup(code: String): String? = when (code) {
    "6203" -> "BEARING-6203"
    "GK40" -> "GASKET-40"
    else -> null
}

fun main() {
    val part: String = "BEARING-6203"     // white card: a String, always present
    val missing: String? = shelfLookup("XX99")
    val found: String? = shelfLookup("GK40")

    println("part length: ${part.length}")
    println("missing length: ${missing?.length}")
    println("missing or dash: ${missing ?: "-"}")

    if (found != null) {
        println("found length: ${found.length}")    // smart cast to String
    }

    val boxed: Any = 42
    println("as? String gave: ${boxed as? String}")
    println("as? Int gave: ${boxed as? Int}")
}

Output:

part length: 12
missing length: null
missing or dash: -
found length: 9
as? String gave: null
as? Int gave: 42

Read the second and third lines together. missing?.length did not throw and did not return a number: the safe call short-circuits, so when the receiver is null the whole expression is null and the type of missing?.length is Int? rather than Int. The elvis operator on the next line takes that null and replaces it with a value you chose, which is why missing ?: "-" has type String and can be used anywhere a white card is accepted. The if (found != null) block needs no cast at all -- inside it, found has type String, because the compiler tracked the check. And as? is the cast that answers null instead of throwing, which makes it the only cast worth writing when the input is genuinely of unknown type.


Technical Depth: What the Compiler Can Prove, and Where the Guarantee Stops

Kotlin's null safety is a static analysis, not a runtime shield. Everything it promises is checked while the compiler holds the whole picture, and everything it cannot see it declines to promise. Learning where the boundary lies matters more than memorising the operators.

The five moves at the hatch

toolon a null receiverresult type given T?reach for it when
?. safe callskips the call entirelyR? where R is the member's typea missing value should propagate as missing
?: elvisevaluates the right-hand sideT if the right side is non-nullyou have a sensible default or an early return
!! assertionthrows NullPointerExceptionTyou can name the invariant that makes null impossible
if (x != null)you write the else branchT inside the blockthe two cases need different logic
as? safe castyields null on a type mismatchT?the runtime type is genuinely unknown

The elvis operator earns a second look, because its right-hand side may be any expression of type Nothing as well as any value: val code = shelfLookup(id) ?: return and ?: throw IllegalStateException("no shelf") both typecheck, and both leave the code after them holding a non-null value. That pattern -- check at the top, exit on absence, work with white cards for the rest of the function -- is the idiom that keeps nullable types from spreading through a codebase.

Where the compiler stops promising

source of the valuewhat the compiler seeswhat can still be null
Kotlin declaration without ?non-null, verifiednothing, within Kotlin
Kotlin declaration with ?nullable, checks requiredthe value itself
unannotated Java methoda platform type, no checks demandedanything; the JVM will throw at the boundary
Java method with @Nullablenullable, checks requiredthe value itself
lateinit var before assignmentnon-null, no checks demandedreading throws UninitializedPropertyAccessException
a value read through reflectionwhatever you cast it toanything
generic T with no boundpossibly nullable, since T defaults to Any?the value; add T : Any to forbid it

The platform-type row is the one that bites in practice. When Kotlin calls unannotated Java, the value arrives with a type the compiler writes as String! and refuses to demand checks for, because insisting on checks for every Java call would make interop unbearable and trusting them blindly would be a lie. The compromise is that the compiler inserts an intrinsic check at the assignment: if you write val s: String = javaCall() and the method returns null, the exception is thrown right there with a message naming the expression, rather than a hundred lines later. Assigning to String? instead moves the decision back under your control.

Smart casts, and the two places they lapse

class Bin(val fixed: String?, var movable: String?)

fun main() {
    val bin = Bin("BEARING-6203", "GASKET-40")

    if (bin.fixed != null) {
        println("fixed: ${bin.fixed.length}")       // smart cast: val, same module
    }

    val snapshot = bin.movable                       // copy the var into a local val
    if (snapshot != null) {
        println("movable: ${snapshot.length}")      // smart cast on the local
    }

    println("via elvis: ${bin.movable?.length ?: -1}")
    bin.movable = null
    println("after clearing: ${bin.movable?.length ?: -1}")
}

Output:

fixed: 12
movable: 9
via elvis: 9
after clearing: -1

The first block smart-casts because fixed is a val with the default getter declared in the same module, so the compiler can prove that no code between the check and the use could change it. The second block cannot: movable is a var, and a var property might be written by another thread, or by a method called in between, so the compiler refuses and tells you so. Copying it into a local val is the fix, and it is not a workaround -- the local genuinely is stable, and the check genuinely does apply to the value you go on to use. The same lapse applies to a val with a custom getter and to any property declared in a different module, where the compiler cannot see whether the getter is stable.

Nullable numbers do not do arithmetic

fun main() {
    val counted = 12
    val maybe: Int? = if (counted > 10) counted else null

    // println(maybe + 1)   // does not compile: no plus operator on Int?
    println("unwrapped: ${(maybe ?: 0) + 1}")
    println("compared safely: ${maybe?.let { it > 5 } ?: false}")
    println("sum of nullables: ${listOf(1, null, 3).filterNotNull().sum()}")
    println("largest present: ${listOfNotNull(1, null, 3).maxOrNull() ?: 0}")
    println("count of holes: ${listOf(1, null, 3, null).count { it == null }}")
}

Output:

unwrapped: 13
compared safely: true
sum of nullables: 4
largest present: 3
count of holes: 2

Int? is not Int with a flag; on the JVM it is a boxed java.lang.Integer reference, and none of the arithmetic operators are declared on it. That is why the commented line is a compile error rather than a silent null-propagating addition, and it is why a nullable numeric field costs an allocation per value where a non-null one costs nothing. The collection helpers exist so you rarely have to unwrap by hand: filterNotNull changes List<Int?> to List<Int> in the type system, and listOfNotNull never builds the holes in the first place.


Real World Example: The Stores Counter's End-of-Day Shortage Report

Every requisition on the day's list has to end up in exactly one of three buckets: issued, short, or not stocked at all. The third bucket is the interesting one, because it is the only one that comes from a null, and because it is genuinely different from a shelf that exists and happens to hold nothing. A part number nobody has ever heard of is a purchasing problem; a bin that has run dry is a replenishment problem. Collapsing them into one number is the kind of mistake a nullable type is there to prevent.

const val REQUISITIONS = "6203:4,GK40:2,XX99:1,SEAL7:3,6203:2"

class Shelf(val code: String, val onHand: Int, val bin: String?)

fun main() {
    val shelves = listOf(
        Shelf("6203", 5, "A1"),
        Shelf("GK40", 0, "B7"),
        Shelf("SEAL7", 9, null)
    )
    val byCode: Map<String, Shelf> = shelves.associateBy { it.code }

    var lines = 0
    var issued = 0
    var shortfall = 0
    var unknown = 0

    for (entry in REQUISITIONS.split(",")) {
        lines++
        val code = entry.substringBefore(":")
        val want = entry.substringAfter(":").toInt()
        val shelf = byCode[code]                 // Map.get returns Shelf?
        if (shelf == null) {
            println("$code: NOT STOCKED (wanted $want)")
            unknown += want
            continue
        }
        val give = if (shelf.onHand >= want) want else shelf.onHand
        println("$code: issue $give of $want from ${shelf.bin ?: "UNBINNED"}")
        issued += give
        shortfall += want - give
    }

    println("--")
    println("lines=$lines issued=$issued shortfall=$shortfall unknown=$unknown")
    println("requested=${issued + shortfall + unknown}")
}

Output:

6203: issue 4 of 4 from A1
GK40: issue 0 of 2 from B7
XX99: NOT STOCKED (wanted 1)
SEAL7: issue 3 of 3 from UNBINNED
6203: issue 2 of 2 from A1
--
lines=5 issued=9 shortfall=2 unknown=1
requested=12

Two nullable values do the work in this program and neither of them was created by anybody setting a variable to null. byCode[code] returns Shelf? because Map.get has no answer for a key that is not present, and bin is declared String? because SEAL7 genuinely sits on a pallet in the yard rather than in a numbered bin. Kotlin forces the two to be handled in different ways, which is appropriate, because they mean different things: the missing shelf changes the control flow, and the missing bin only changes what gets printed.

The early continue is worth more than it looks. After that block, shelf has type Shelf rather than Shelf? for the whole rest of the loop body, so shelf.onHand and shelf.bin need no further ceremony. This is the check-at-the-top idiom, and it is why the interesting lines of a well-written Kotlin function tend to be free of question marks even when its inputs are full of them. The alternative, wrapping the remaining twenty lines in if (shelf != null) { ... }, indents the body for no gain.

The arithmetic reconciles, and that is the point of printing it. Every requisition contributed its wanted quantity to exactly one of three counters, so issued + shortfall + unknown must equal the total quantity requested, which is 4 plus 2 plus 1 plus 3 plus 2, or 12. A report that does not balance is a report with a bucket missing, and printing the reconciliation is how you find out on the first run rather than at the month end.

The limits are real and one of them is a defect rather than a rough edge. The design flaw is that stock is never decremented: byCode is built once from immutable Shelf objects, so the two 6203 lines each see onHand as 5 and the program cheerfully issues 6 units from a shelf holding 5. Nothing about null safety protects against this, because nothing here is null -- the bug is that the model has no notion of a reservation, and a report that can promise more than exists is worse than no report. Fixing it means either aggregating requisitions by code before issuing, or holding a mutable remaining quantity per shelf and writing to it as lines are processed. Beyond that: toInt() throws NumberFormatException on any malformed line, so one bad character in the input file takes the whole report down; shortfall conflates "partly filled" with "nothing available", so GK40 at zero looks the same in the totals as a shelf that could supply one of two; associateBy silently keeps the last entry when two Shelf objects share a code, which would hide a duplicate stock record rather than report it; and a negative quantity in the input would be added to issued and pass the reconciliation check untouched.


Common Mistakes

  1. Reaching for !! because the compiler complained. The assertion operator does not fix a nullability problem; it moves the report of that problem from compile time to runtime and deletes the information about where the null came from. Write it only where you can state the invariant out loud -- "this was assigned in onCreate" -- and prefer ?: error("message") when you want the crash but also want it to say why.
  1. Using ?. where the null case actually matters. order?.dispatch() silently does nothing when order is null, and silence is the wrong answer when a missing order means a lost shipment. A safe call is right when absence should propagate; when absence is an error, an if or an elvis-with-throw makes the decision visible in the code.
  1. Comparing a nullable to a literal and expecting a smart cast to survive. if (x != null) { ... } smart-casts, but if (x?.isEmpty() == false) { ... } does not make x non-null inside the block, because the compiler tracked the result of the call rather than the receiver. Check the receiver explicitly, or restructure with x?.let { }.
  1. Assuming a var property can be smart cast. After if (config.name != null) the compiler still treats config.name as nullable if name is a var, and the error message about a "custom getter or mutable property" is easy to misread as a compiler limitation. It is not: another thread really could write between the two lines. Copy to a local val first.
  1. Letting platform types in from Java without a decision. val name: String = javaObject.getName() compiles with no complaint and throws at that line if Java returns null. It is not wrong to write it -- an intrinsic check there is exactly what you want -- but doing it by accident means you never considered the nullable alternative. Annotate the Java side, or declare the Kotlin side String? deliberately.
  1. Treating a null and an empty value as the same case. name?.isEmpty() ?: true and name.isNullOrEmpty() happen to agree; stock == null and stock == 0 do not, and the shortage report above only works because it keeps them apart. Decide whether absence and emptiness mean the same thing in your domain before you collapse them, and use isNullOrEmpty or isNullOrBlank when they genuinely do.
  1. Declaring numeric fields nullable out of habit. Int? boxes on the JVM, cannot be used with the arithmetic operators, and turns a four-byte field into a reference plus an object. In a list of a million records that is a measurable cost. If zero or -1 is a legitimate sentinel in your domain, use it; if absence is genuinely meaningful, pay for the box on purpose.
  1. Forgetting that a generic T includes null. fun <T> firstOrNull(items: List<T>): T? looks like it constrains nothing, and it does not: the default upper bound of a type parameter is Any?, so T can be String? and T? can be String??, which collapses to one level of nullability. Write <T : Any> when the values themselves must be present.
  1. Chaining safe calls until the whole expression means nothing. a?.b?.c?.d ?: default compiles, and it also erases four different reasons for the default -- you cannot tell from the result whether a was missing or d was. When the chain matters, break it up and name the step that failed; when it does not, the chain is fine and the shorter code wins.

Best Practices

  • Make nullability a modelling decision, not an afterthought. Ask what absence means in the domain -- not stocked, not yet measured, deliberately blank -- and let the answer choose between T?, a sentinel value, and a sealed type with a named case for each kind of absence.
  • Narrow at the boundary and keep the interior non-null. Validate and unwrap the moment a value enters your code, then pass String rather than String? inward. Nullability that reaches the fifth layer of a call stack is nullability nobody checked at the first.
  • Prefer ?: return, ?: continue and ?: error(...) over nesting. The elvis operator accepts any expression of type Nothing on its right, so the guard costs one line and leaves the rest of the function reading as if the value had never been optional.
  • Use ?.let { } for a block that should run only when the value is present, and a plain if when you also need an else. let returns the block's value, which makes it a good fit inside an expression and a poor one when you are only performing a side effect on two branches.
  • Reserve !! for invariants you can name, and put the name in the code. checkNotNull(binding) { "view accessed before onCreateView" } costs the same as binding!! and produces a failure a colleague can act on at three in the morning.
  • Reach for as? instead of as whenever the runtime type is not already guaranteed by a check. The two differ only in the failure mode, and one of them can be handled with an elvis while the other can only be caught.
  • Annotate any Java you own with @Nullable and @NotNull, or add a package-level default. Kotlin honours the annotations from JSR-305, JetBrains, Android and several other families, and each one converts a platform type into a real Kotlin type at no runtime cost.
  • Let the standard library do the unwrapping in collection code. filterNotNull, listOfNotNull, mapNotNull and firstOrNull express intent more precisely than a loop with a null check, and they change the element type in the signature so the next stage of the pipeline needs no checks at all.

Practice Exercises

  1. Write fun bin(code: String): String? that returns a bin for two known codes and null otherwise. In main, print the result for a known and an unknown code four ways: with a safe call to length, with an elvis default, inside an if (x != null) block, and with ?.let. State in a comment which of the four produce a non-null type for the rest of the expression.
  1. Take the shortage report and fix its stock-decrement flaw. Change Shelf.onHand to a var, subtract each issue from it, and re-run the same requisition string. Print the new totals and explain in a comment why the second 6203 line now behaves differently and whether the reconciliation total changed.
  1. Write a class Reading(val sensor: String, val celsius: Double?) and a list containing at least two readings with a null temperature. Produce three numbers with no explicit loop: the count of readings, the count of readings that carry a temperature, and the average of the temperatures that are present. Use mapNotNull or filterNotNull rather than !!, and print all three on one line.
  1. Declare fun <T> secondOrNull(items: List<T>): T? and call it with a List<String?> that has null as its second element. Print the result and explain in a comment why it is impossible for the caller to distinguish "there was no second element" from "the second element was null". Then write fun <T : Any> secondOrNull2(items: List<T>): T? and state what the bound bought you.