Search⌘ K
AI Features

Introduction to the Nothing Type

Learn about Kotlin's Nothing type, an uninhabited subtype used for functions that never return like throw or TODO. Understand how it improves type inference, signifies unreachable code, and integrates with Kotlin’s type system and coroutines.

The Nothing type is a subtype of all the types in Kotlin. If we had an instance of this type, it could be used instead of everything else (like a Joker in the card game Rummy). It’s no wonder that such an instance does not exist. The Nothing type is an empty type (also known as a bottom type, zero type, uninhabited type, or never type), which means it has no values.

It is literally impossible to make an instance of the Nothing type, but this type is still really useful. Some functions declare Nothing as their result type. We’ve likely used such functions many times already.

1.

What functions are those?

Show Answer
1 / 2

In all cases, they never return, so the Nothing type is not only valid but also really useful.

Kotlin 1.5
fun runForever(): Nothing {
while (true) {
// no-op
}
}
fun endProgram(): Nothing {
exitProcess(0)
}
fun fail(): Nothing {
throw Error("Some error")
}

Commonly used Nothing functions

We have never found a good use case for a function that runs forever, and ending a program is not very common, but we often use functions that throw exceptions. Who hasn’t ever used TODO()? This function throws a NotImplementedError exception. There is also the error function from the standard library, which throws an IllegalStateException.

Kotlin 1.5
inline fun TODO(): Nothing = throw NotImplementedError()
inline fun error(message: Any): Nothing =
throw IllegalStateException(message.toString())
  • We use TODO as a ...