Skip to Content
Course content

144: Nothing Type and Its Uses

Click on the "Edit" button in the top corner of the screen to edit your slide content.

You've likely encountered Unit a thousand times—it's basically Kotlin's version of void. It means "this function does its job and returns nothing of value." But there is a much weirder, more powerful type called Nothing. If Unit is a value that says "I'm done," Nothing is a type that says "I will never ever return."

Let's look at a common mistake when building validation helpers. I used to do this all the time when I first started with Kotlin.

The Type Mismatch in our Error Helper

fun fail(message: String): Unit {
    throw IllegalArgumentException(message)
}

fun getConfiguration(key: String): String {
    val configMap = mapOf("api_url" to "https://api.example.com")
    
    return if (configMap.containsKey(key)) {
        configMap[key]!!
    } else {
        fail("Missing configuration key: $key") 
        // ERROR: Type mismatch. 
        // Required: String, Found: Unit
    }
}

The logic seems sound to a human. We know that if fail() is called, an exception is thrown and the program (or at least this thread) stops. The function getConfiguration will never actually return a value if that else block is hit. But the Kotlin compiler isn't a psychic; it just sees that the if branch returns a String and the else branch returns Unit. Since Unit isn't a String, the code won't compile.

Switching to the Bottom Type

To fix this, we change the return type of our helper from Unit to Nothing. This tells the compiler that this function is a "dead end."

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

fun getConfiguration(key: String): String {
    val configMap = mapOf("api_url" to "https://api.example.com")
    
    return if (configMap.containsKey(key)) {
        configMap[key]!!
    } else {
        fail("Missing configuration key: $key") // This now works!
    }
}

Now it compiles perfectly. Why? Because Nothing is what we call a bottom type. In the Kotlin type hierarchy, Nothing is a subtype of every other type. It is a subtype of String, Int, UserAccount, and even Any. Because it's a subtype of String, the compiler allows it to be returned where a String is expected.

Why Nothing is Different from Unit

I'll be honest: the distinction feels academic until you hit a bug like the one above. But here is the mental model I use: Unit is a value (a singleton object) that represents the absence of a meaningful result. Nothing is a type that represents the absence of a value entirely.

  • Unit: "I finished my work, here is a token saying I'm done."
  • Nothing: "I crashed, I looped forever, or I jumped to another part of the program. I am never coming back to this line of code."

This has a massive impact on how the compiler treats the code following a Nothing call. If you call a function that returns Nothing, the compiler knows that any code after that call is unreachable.

Handling Infinite Loops and Divergence

While throwing exceptions is the most common use, Nothing is also used for functions that diverge—meaning they enter an infinite loop and never return control to the caller. You might see this in a low-level event loop or a custom runtime kernel.

fun startEventLoop() {
    while (true) {
        // Process events forever
        // This function technically never "returns"
    }
}

If you wanted to be explicit for other developers (and the compiler), you could define that return type as Nothing. It serves as a warning: "If you call this, don't expect the next line of your code to ever execute."




📋 Practical Task

Implementing a Strict Requirement Validator

You are building a system that processes User profiles. You need to create a "Strict Validator" that ensures required fields are present. If a field is missing, the system should throw a custom MissingFieldException and stop execution immediately.

Your task:

  1. Create a custom exception class called MissingFieldException.
  2. Write a function called requireNotNullValue that takes a value (nullable) and a field name.
  3. The function should return the non-null value if it exists, or call a helper function called throwFatalError if it is null.
  4. Implement throwFatalError using the Nothing type to ensure the compiler understands that execution stops there.

Ensure that your requireNotNullValue function can be used inside a variable assignment without causing a type mismatch error.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.