liveBook · Manning

Kotlin

As explained in The Art of Code

A statically typed programming language that runs on the JVM and provides explicit nullability in its type system.

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

How The Art of Code covers it

How deep it goes
Explains nullability, safe calls, Elvis fallback, smart casts, and sealed when exhaustiveness through comparative code examples.
Examples
Uses product pricing chains and Book subtype promotion messages as concrete examples of concise, safe control flow.
What you can do after
Evaluate Kotlin designs for readability, cognitive complexity, null-safety, and compiler-enforced coverage of sealed cases.
How it connects
Connects nullability with safe-call operators and Elvis expressions, and connects sealed hierarchies with when expressions and smart casts.

Also explained in

Compare how 2 books explain Kotlin →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Art of Code. The section links point to the parts of the book it draws on.