Kotlin makes absence explicit in the type system: nullable values use ?, and unsafe access is rejected until the possibility of absence is handled. The safe-call operator ?. and Elvis operator ?: keep a business rule visible instead of burying it beneath repeated defensive checks. section 1.2
Use Kotlin’s control-flow features to keep code close to the domain:
- Prefer safe calls and Elvis fallback when traversing possibly absent objects, such as choosing a discounted price or falling back to a base price. section 1.2
- Use smart casts with if/else when conditions are simple and direct; this avoids temporary mutable variables and explicit casts. section 5.1.3
- Prefer when over chained if/else for a sealed hierarchy: the expression mirrors the domain and the compiler verifies that every subtype is handled. section 5.1.4
Selecting a product price
A nullable chain can express the rule directly: obtain the discounted amount when available, otherwise obtain the base amount. The result remains nullable when no usable price exists, so callers must account for that outcome. section 1.2
Listing 5.4 Selecting a promotional message with Kotlin when and a sealed hierarchy
fun getPromotionalMessage(book: Book): String =
when (book) {
is DigitalBook -> book.downloadLink
is PocketBook -> "Same book, smaller format!"
is HardcoverBook -> "Old-fashioned book…"
}
Inspect a concise when expression that maps each Book subtype to its promotional message and gains compiler-checked exhaustiveness from a sealed hierarchy. section 5.1.4

