Part 1 · 1 chapters · ~8 min
The Type System and Null Safety
Nullable and non-null types, safe calls, the Elvis operator and smart casts, !! and when it is justified, platform types from Java, sealed classes and interfaces with exhaustive when, value classes for ids and money, generics with declaration-site variance, reified type parameters, and type inference limits.
2
Making illegal states unrepresentable
code
sealed interface Payout {
val id: String
data class Pending(override val id: String) : Payout
data class Settled(override val id: String, val railRef: String) : Payout
data class Failed(override val id: String, val reason: String) : Payout
}
fun label(p: Payout): String = when (p) { // exhaustive: no else needed
is Payout.Pending -> "Processing"
is Payout.Settled -> "Sent (${p.railRef})" // smart cast: railRef available
is Payout.Failed -> "Failed: ${p.reason}"
}
@JvmInline value class AccountId(val raw: String) // a distinct type, no runtime wrapper
@JvmInline value class Kobo(val value: Long) { operator fun plus(o: Kobo) = Kobo(value + o.value) }
val name: String? = user.preferredName
val shown = name?.trim()?.takeIf { it.isNotEmpty() } ?: user.fullName // safe calls + ElvisTHE TYPE SYSTEM AND NULL SAFETY
types that rule out whole classes of bugs
swipe the figure sideways, or tap expand for full screen
1/4
null safety
String cannot hold null; String? can, and the compiler refuses calls on it until you check. Tony Hoare called null references his "billion-dollar mistake"; Kotlin puts them in the type system.
nulls tracked by the compilerthe billion-dollar mistake