...

/

Introduction to the Nothing Type

Introduction to the Nothing Type

Explore the pivotal role of the Nothing type in handling exceptions, non-terminating scenarios, and type hierarchy, including its interactions with null values.

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
Q1 / Q2

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

Press + to interact
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.

Press + to interact
inline fun TODO(): Nothing = throw NotImplementedError()
inline fun error(message: Any): Nothing =
throw IllegalStateException(message.toString())
  • We use TODO as a ...