← Back to Kotlin Course | Chapter 2: Variables & Types | Lesson 6 of 7

The Nothing Type

The Nothing type is Kotlin's way of marking code paths, like throwing an error, that never actually finish or return a normal value.

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

markup
fun fail(message: String): Nothing {
    throw IllegalStateException(message)
}

fun main() {
    try {
        fail("Something went wrong")
    } catch (e: IllegalStateException) {
        println("Caught: ${e.message}")
    }
}

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

markup
fun getOrDefault(value: Int?): Int {
    return value ?: throw IllegalArgumentException("value was null")
}

fun main() {
    println(getOrDefault(5))
}

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

markup
fun plannedFeature(): Int {
    return try {
        TODO("implement this later")
    } catch (e: NotImplementedError) {
        -1
    }
}

fun main() {
    println("Placeholder result: ${plannedFeature()}")
}
Common Mistakes
  1. Confusing Nothing with null or with Unit; Nothing means a function never completes normally, while Unit means it completes but returns no useful value.
  2. Not realizing that a function like TODO() returns Nothing, which is why it can be used anywhere a value is expected without a type error.
  3. Trying to create an instance of Nothing; it has no instances -- it exists only to describe code that never returns.
Chapter Summary
  • Nothing is 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 of Nothing.
  • Because Nothing is 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 returns Nothing, 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.