liveBook · Manning

Missing value

As explained in Kotlin in Action, 2E

A null value represents the absence of an object or reference value in a program.

A missing value is represented by null, meaning that an object or reference value is absent. Kotlin makes this possibility explicit: ordinary types cannot contain null, while a question mark marks a nullable type such as String?. section 7.2

Handling a nullable string

A String? parameter may contain null, so Kotlin requires a check before accessing length. The example returns 0 for null and 3 for "abc"; a String parameter would reject null at compile time. section 7.2

Listing 7.1 Handling null values using if checks
fun strLenSafe(s: String?): Int =
    if (s != null) s.length else 0   #1
 
fun main() {
    val x: String? = null
    println(strLenSafe(x))
    // 0
    println(strLenSafe("abc"))
    // 3
}

Use this runnable example to connect nullable declarations, an if check, and the resulting values. section 7.2

Kotlin applies the rule consistently:

  • Declaring a parameter as String guarantees that it contains a String instance. section 7.2
  • Declaring a value as String? allows null, but direct method calls on it are rejected. section 7.2
  • Passing a nullable value to a non-null parameter produces a compile-time type mismatch rather than a likely runtime NullPointerException. section 7.2 section 1.3.1
  • This differs from familiar Java code, where calling length on a null String can throw NullPointerException at runtime. section 7.2

How Kotlin in Action, 2E covers it

How deep it goes
Explains nullable declarations, compiler rejection, and an if-check implementation, without detailing safe-call or non-null-assertion semantics.
Examples
Uses Java and Kotlin string-length functions, nullable String? variables, null arguments, and an if-check returning 0 or 3.
What it assumes
Contrasts basic Java null handling while teaching Kotlin's nullable and non-nullable types explicitly.
What you can do after
Apply Kotlin's nullable-type rules to declare parameters, interpret compiler errors, and handle null with an explicit check.
How it connects
Connects missing values with nullable types, type checking, NullPointerException, Java interoperability, and Kotlin's type system.

Also explained in

Compare how 35 books explain missing value →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Kotlin in Action, 2E. The section links point to the parts of the book it draws on.