Kotlin
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Null Safety
-
Section 4: Object-Oriented Kotlin
-
Section 5: Functional Kotlin
-
Section 6: Coroutines
-
Section 7: Collections Deep Dive
-
Section 8: Type System Deep Dive
-
Section 9: Interop and Tooling
-
Section 10: Kotlin DSLs and Patterns
-
Section 11: Testing and Quality
-
Section 12: Server-Side Kotlin
-
Section 13: Practical Projects
-
Section 14: Interview Practice
-
Section 15: More Practice Exercises
-
Section 16: More Standard Library
-
Section 17: Multiplatform Kotlin
-
Section 18: kotlin.collections In Depth
-
Section 19: kotlin.text In Depth
-
Section 20: kotlin.ranges and kotlin.sequences
-
Section 21: kotlin.io and File Handling
-
Section 22: kotlinx.coroutines Deep Dive
-
Section 23: kotlin.reflect
-
Section 24: Android Development with Kotlin Overview
-
Section 25: Kotlin Multiplatform Deep Dive
-
Section 26: Kotlin for Backend Deep Dive
-
Section 27: Kotlin Design Patterns
-
Section 28: Advanced Language Features
-
Section 29: More Practice Exercises
-
Section 30: More Interview Practice
-
Section 31: Kotlin Type System Deep Dive
-
Section 32: Kotlin Null Safety Advanced
-
Section 33: Kotlin Testing Deep Dive
-
Section 34: Kotlin Build Tooling Deep Dive
-
Section 35: Kotlin Serialization
-
Section 36: Kotlin Performance Considerations
-
Section 37: Kotlin Native Overview
-
Section 38: Kotlin for Data and Scripting
-
Section 39: More Coroutines Practice
-
Section 40: More Android-Adjacent Patterns
-
Section 41: More Practical Projects
-
Section 42: More Design and Architecture Practice
-
Section 43: Kotlin Language Evolution
-
Section 44: More Interview and Review
-
Section 45: Kotlin Delegation Patterns Deep Dive
-
Section 46: Kotlin Annotations Deep Dive
-
Section 47: Kotlin for Gradle Plugin Development
-
Section 48: Kotlin Concurrency Beyond Coroutines
-
Section 49: Kotlin Compiler Internals
-
Section 50: Real-World Kotlin Case Studies
-
Section 51: Final Practice Projects
-
Section 52: Kotlin for Server-Side Reactive Programming
-
Section 53: More Practice and Drills
-
Section 54: Kotlin Security Practices
144: Nothing Type and Its Uses
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:
- Create a custom exception class called
MissingFieldException. - Write a function called
requireNotNullValuethat takes a value (nullable) and a field name. - The function should return the non-null value if it exists, or call a helper function called
throwFatalErrorif it is null. - Implement
throwFatalErrorusing theNothingtype 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.
There are no comments for now.