The Nothing Type
What Nothing Represents
Nothing is a special type that has no values at all. It signals that a function will never return normally -- it either throws an exception or loops forever.
Example: What Nothing Represents
fun fail(message: String): Nothing {
throw IllegalStateException(message)
}
fun main() {
try {
fail("Something went wrong")
} catch (e: IllegalStateException) {
println("Caught: ${e.message}")
}
}
Login to try C/C++/Java/PHP code in the editor
Nothing as a Subtype of Everything
Because Nothing is a subtype of every other type in Kotlin, an expression of type Nothing can be used anywhere a value of any type is expected, letting the compiler treat both branches consistently.
Example: Nothing as a Subtype of Everything
fun getOrDefault(value: Int?): Int {
return value ?: throw IllegalArgumentException("value was null")
}
fun main() {
println(getOrDefault(5))
}
Login to try C/C++/Java/PHP code in the editor
TODO() Returns Nothing
The standard library's TODO() function has a return type of Nothing and throws a NotImplementedError, letting you stub out a function body while still satisfying the compiler's type checks.
Example: TODO() Returns Nothing
fun plannedFeature(): Int {
return try {
TODO("implement this later")
} catch (e: NotImplementedError) {
-1
}
}
fun main() {
println("Placeholder result: ${plannedFeature()}")
}
Login to try C/C++/Java/PHP code in the editor
- Confusing
Nothingwithnullor withUnit;Nothingmeans a function never completes normally, whileUnitmeans it completes but returns no useful value. - Not realizing that a function like
TODO()returnsNothing, which is why it can be used anywhere a value is expected without a type error. - Trying to create an instance of
Nothing; it has no instances -- it exists only to describe code that never returns.
Nothingis a type with no instances, used to represent an expression that never completes normally.- Functions that always throw an exception, like ones ending in
throw, have an inferred return type ofNothing. - Because
Nothingis a subtype of every other type, it can be used anywhere any type is expected, such as after??in the Elvis operator. TODO()from the standard library returnsNothing, letting you stub out unfinished code that still type-checks.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: