The Analogy: The Machine-Shop Emergency Stop
Every machine on a shop floor has an emergency stop -- a red mushroom button that, when struck, halts the machine dead. What matters about the E-stop is that control does not resume on the far side of it: the next step in the machine's cycle simply never runs, because the cycle has been cut. Kotlin's Nothing type is the type of an operation that behaves like striking that button. A function whose return type is Nothing never hands control back to the line after the call; it always ends the flow, by throwing or by looping forever, so there is no "afterward" to speak of.
The E-stop also produces no product. A normal station yields a finished part into the bin beside it, but the E-stop yields nothing at all -- the bin stays empty because the machine stopped rather than completing a piece. This is why Nothing has no instances: no value of type Nothing can ever exist, because a Nothing-typed expression never completes to produce one. It is the type of a result that will never arrive.
Here is the property that makes Nothing genuinely useful. The very same E-stop button design can be wired into any machine, at any point in any cycle, no matter what that station was supposed to produce next -- a lathe, a press, a grinder. It fits everywhere because it never outputs a part that could be the wrong kind; it outputs no part. In type terms, Nothing is a subtype of every type, so a call that returns Nothing slots into any position that expects any type. That is exactly what lets throw sit on the right of an Elvis operator or in one branch of an if that must yield an Int: the E-stop fits the slot because it never clashes with it.
There is also a commissioning placeholder: a red "STATION NOT COMMISSIONED" stop that halts the line with a clear message if any part ever reaches it, marking work that is planned but not yet built. Kotlin's TODO() is this stub -- it has return type Nothing and throws a "not implemented" error, letting unfinished code type-check while guaranteeing a loud failure if it runs. The failures around all this are twofold. The first is the engineer who writes cycle steps after an unconditional stop and expects them to execute: they are dead steps that never run, the compiler's unreachable-code warning made physical. The second is shipping a line with a "not commissioned" stop still in place -- leaving a TODO() in production, so the first real part to arrive halts everything.
Syntax or Core Structure
A function that always ends the flow -- by throwing -- is declared to return Nothing. Because Nothing is a subtype of every type, a call to it fits wherever any type is expected.
fun fail(reason: String): Nothing = throw IllegalStateException(reason)
fun sqrtLabel(n: Int): String =
if (n >= 0) "ok " + n
else fail("negative: " + n)
fun main() {
println(sqrtLabel(9))
val msg = try {
sqrtLabel(-4)
} catch (e: IllegalStateException) {
"caught " + e.message
}
println(msg)
}
Output:
ok 9
caught negative: -4
fail returns Nothing, so the else branch of sqrtLabel type-checks even though the if branch yields a String -- Nothing fits where a String is expected because it is a subtype of everything. sqrtLabel(9) takes the if branch and returns "ok 9". sqrtLabel(-4) calls fail, which throws IllegalStateException; the catch reports "caught negative: -4". The compiler also knows that after fail(...) control cannot continue, so it treats the whole else as terminating -- no bogus "missing return" error appears.
Technical Depth: Nothing, Unit, and Flow
Nothing versus Unit and Nothing?
Three easily-confused types sit near each other. The table pins down what each means.
| Type | Instances | Meaning |
|---|---|---|
Unit | one (Unit) | function returns normally, no useful value |
Nothing | none | function never returns normally |
Nothing? | one (null) | the type whose only value is null |
Any | all non-null | supertype of everything non-null |
Unit is what most "void" functions return -- they do finish. Nothing is the opposite end: the function does not finish at all. And Nothing? is a curiosity that shows up in inference, since the only thing that is a Nothing? and not a Nothing is null.
The compiler tracks that Nothing ends the flow
Because a Nothing-returning call cannot return, the compiler treats code after it as unreachable and uses that fact for smart casts.
fun fail(msg: String): Nothing = throw IllegalArgumentException(msg)
fun lengthOf(s: String?): Int {
if (s == null) fail("null input")
// after fail(), s is smart-cast to non-null String here
return s.length
}
fun main() {
println(lengthOf("hello"))
}
Output:
5
The if (s == null) fail(...) has no return, yet after it the compiler knows s cannot be null -- if it had been, fail would have ended the function. So s is smart-cast to non-null String, and s.length compiles without a ?. or !!. lengthOf("hello") returns 5. The Nothing return type is what carries the "this path terminates" information to the flow analysis.
TODO marks unfinished code
TODO() returns Nothing and throws NotImplementedError, so it satisfies any return type while flagging work not yet done.
fun computeTax(amount: Int): Int = TODO("tax rules pending")
fun main() {
val outcome = try {
computeTax(100)
} catch (e: NotImplementedError) {
"not implemented yet"
}
println(outcome)
}
Output:
not implemented yet
computeTax is declared to return Int, but its body is TODO(...), which type-checks because TODO returns Nothing and Nothing fits an Int return. Calling it throws NotImplementedError, caught here and reported as "not implemented yet". This lets you stub a function with the right signature and compile the surrounding code, while guaranteeing a loud, unmistakable failure if the stub is ever actually invoked.
Nothing as a bottom type in inference
Because Nothing is a subtype of every type, a List<Nothing> is a subtype of List<T> for any T, which is why an empty list unifies with any element type, and why a throw branch never widens an expression's type.
fun main() {
val empty = emptyList<Nothing>()
val ints: List<Int> = empty
val strs: List<String> = empty
println("empty sizes: " + ints.size + " " + strs.size)
val n: Int = if (true) 5 else throw RuntimeException("unreachable")
println("n = " + n)
}
Output:
empty sizes: 0 0
n = 5
emptyList<Nothing>() has type List<Nothing>, and because List is covariant and Nothing is a subtype of both Int and String, that one empty list can be assigned to List<Int> and List<String> alike -- both report size 0. In the second statement, the if must produce an Int; the then branch yields 5 and the else branch is a throw of type Nothing, which does not force the result type any wider than Int, so n is cleanly typed Int and equals 5. The bottom-type nature of Nothing is what makes both of these type-check without ceremony.
error() as a Nothing-returning else
The standard error(message) function returns Nothing and throws IllegalStateException, making it a tidy terminating branch in a when.
fun grade(score: Int): String = when {
score >= 90 -> "A"
score >= 80 -> "B"
score >= 0 -> "C"
else -> error("negative score: " + score)
}
fun main() {
println(grade(95))
println(grade(72))
val msg = try {
grade(-1)
} catch (e: IllegalStateException) {
"rejected: " + e.message
}
println(msg)
}
Output:
A
C
rejected: negative score: -1
grade(95) matches the first branch for "A"; grade(72) falls through to score >= 0 for "C". The else branch calls error(...), which returns Nothing, so the when still type-checks as returning String even though that branch yields no string. grade(-1) triggers it, throwing IllegalStateException with "negative score: -1", caught and reported as "rejected: negative score: -1". Using error() here is more concise than throw IllegalStateException(...) and signals "this state should be impossible" at a glance. It reads as an assertion about the code's own invariants rather than an expected outcome, which is the right tone for a branch you never intend to reach.
Real World Example: A Command Router
A service routes text commands to handlers. Two commands are implemented, and the author uses TODO() in the else branch as a reminder to handle the rest later. The code compiles, the two known commands work, and it ships.
fun handle(command: String): String =
when (command) {
"start" -> "starting"
"stop" -> "stopping"
else -> TODO("other commands") // placeholder left in
}
fun main() {
println(handle("start"))
println(handle("stop"))
val result = try {
handle("pause")
} catch (e: NotImplementedError) {
"crashed on: pause"
}
println(result)
}
Output:
starting
stopping
crashed on: pause
The implemented commands behave correctly. handle("start") matches the first branch and returns "starting"; handle("stop") returns "stopping". Any test that exercises only these two passes cleanly, and the TODO() in the else is invisible because those tests never reach it.
Then a real "pause" command arrives. It matches no explicit branch, falls into else, and evaluates TODO(...), which throws NotImplementedError -- here caught and reported as "crashed on: pause". In production without that catch, this is a hard crash on ordinary input. The placeholder that felt harmless during development is a live landmine on the else path.
The genuine design flaw is using TODO() as a runtime default for a reachable case, which turns "not yet implemented" into "crashes when used." It is the analogy's not-commissioned stop shipped to opening night: correct-looking until the first real part reaches it. TODO() returns Nothing, so it satisfies the String return type and compiles silently -- the very convenience that lets it stub code is what lets it slip into production undetected. The fix depends on intent: if unknown commands are legitimate, replace the TODO() with a real default such as returning an error string or a Result failure; if the command set is meant to be closed, model it as a sealed type or enum so the when becomes exhaustive and the compiler forces every case, eliminating the else entirely. The broader limitation is that Nothing makes a stub type-compatible with everything, so a TODO() never fails to compile -- it only fails to run, and only when someone finally hits that path.
Common Mistakes
- Leaving
TODO()on a reachable path.TODO()compiles because it returnsNothing, but it throwsNotImplementedErrorif run. Shipping one on a live branch turns ordinary input into a crash.
- Confusing
NothingwithUnit.Unitmeans the function returns normally with no useful value;Nothingmeans it never returns. A cleanup function should returnUnit, notNothing.
- Writing code after a
Nothing-returning call. Statements afterthrow,fail(...), orexitProcess(...)are unreachable. The compiler warns, and the code will never run.
- Declaring
Nothingas a parameter or field type. SinceNothinghas no instances, a parameter of typeNothingcan never be supplied. It is a return type for non-returning functions, not a value type.
- Forgetting that
Nothingpowers smart casts. Afterif (x == null) fail(),xis non-null below -- but only iffailreturnsNothing. Declaring itUnitbreaks the smart cast.
- Using
Nothing?by accident. An inferredNothing?(often from a lonenull) means "only null can go here," which is rarely intended. Give such values an explicit type.
- Throwing where a real value was expected as normal flow. A
Nothing-returning helper is for exceptional termination; using it for ordinary "no result" cases is better served by a nullable or a sealed result.
- Assuming an empty collection literal has a useful element type.
emptyList()may inferList<Nothing>, which unifies with any element type but carries no elements; specify the type when it matters.
- Relying on
TODO()messages as documentation. The message is only seen if the stub is hit at runtime. Track unfinished work in the issue tracker, not solely in aTODO()string.
Best Practices
- Use a
Nothing-returning helper likefun fail(msg: String): Nothingto centralise "this cannot continue" logic and enable smart casts after it. - Reserve
TODO()for genuinely unreachable-during-development stubs, and never let one survive on a path real input can take. - Prefer modelling a closed set of cases as a
sealedtype orenumso awhenis exhaustive, removing the need for a placeholderelse. - Return
Unitfor functions that finish without a value andNothingonly for those that never finish. - Let
throwandNothing-returning calls sit directly in expressions (Elvis,ifbranches) where their bottom-type nature keeps the code concise. - Trust and heed the unreachable-code warning; if code after a call is flagged dead, the call returns
Nothing. - Give lone
nulls and empty literals explicit types when inference would otherwise land onNothingorNothing?. - Track unfinished features in real tooling, using
TODO()as a compile aid rather than a substitute for planning.
Practice Exercises
- Write
fun fail(msg: String): Nothingand use it on theelseof awhenthat must return anInt, confirming thewhencompiles becauseNothingfits theIntslot.
- Show the smart-cast effect: write
if (x == null) fail(...)with noreturn, then usexas non-null below, and confirm it compiles only becausefailreturnsNothing.
- Reproduce the
TODO()flaw: putTODO()on theelseof a commandwhen, show the known commands work and an unknown one throwsNotImplementedError, then fix it with a graceful default or asealed/enumcommand type.
- Write a function returning
Unitand another returningNothing, and explain from their bodies why one finishes and the other cannot.