0
0
KotlinConceptBeginner · 3 min read

What is Nothing Type in Kotlin: Explanation and Examples

In Kotlin, Nothing is a special type that represents the absence of a value and never returns normally. It is used to indicate that a function never completes normally, such as when it always throws an exception or enters an infinite loop.
⚙️

How It Works

Imagine you have a function that never finishes its job in the usual way. For example, it might always throw an error or keep running forever. In Kotlin, the Nothing type is used to mark such functions. It tells the program, "This function will never give you a value because it never ends normally."

Think of Nothing as a black hole in your code: once you enter it, you never come back with a result. This helps Kotlin understand that after calling such a function, the rest of the code won’t run, so it can avoid unnecessary checks or warnings.

Because Nothing has no values, it can fit anywhere a value is expected, making it very useful for signaling errors or infinite loops without breaking type rules.

đź’»

Example

This example shows a function that always throws an exception and returns Nothing. The compiler knows this function never returns normally.

kotlin
fun fail(message: String): Nothing {
    throw IllegalArgumentException(message)
}

fun main() {
    val x: Int = 10
    if (x < 0) {
        fail("x must not be negative")
    } else {
        println("x is $x")
    }
}
Output
x is 10
🎯

When to Use

Use Nothing when you want to mark functions that never return normally, such as those that always throw exceptions or run forever. This helps the compiler understand your code flow better and avoid unreachable code warnings.

For example, if you write a function to stop the program with an error message, declare it to return Nothing. This clearly shows that the function will not return a value and the program will not continue past it.

It is also useful in control flow to signal that some branches do not return, making your code safer and easier to read.

âś…

Key Points

  • Nothing means no value and no normal return.
  • Used for functions that always throw exceptions or never finish.
  • Helps Kotlin understand code flow and avoid unreachable code.
  • Can be used anywhere a value is expected because it has no instances.
âś…

Key Takeaways

Nothing represents a function that never returns normally.
It is useful for functions that always throw exceptions or loop forever.
Using Nothing helps Kotlin understand program flow better.
Nothing has no values but fits anywhere a value is expected.
Declare functions returning Nothing to signal no normal completion.