Careeroza
Unit and Nothing
Unit
Example
A function that returns no useful value returns Unit (like void in Java). You normally do not write it. Unit is a real object, so it can be printed.
fun logEvent(name: String): Unit {
println("Event: $name")
}
fun logEvent2(name: String) { // Unit is implied
println("Event: $name")
}
fun main() {
logEvent("app_open")
val result = logEvent2("add_to_cart")
println(result)
}Output
Event: app_open Event: add_to_cart kotlin.Unit
Nothing
Nothing is the return type of a function that never returns normally: it always throws an exception or loops forever. The compiler knows the code after it cannot run. TODO() and error() in the standard library return Nothing.
Example
Because fail() returns Nothing, it can be used on the right side of ?:, and user becomes a non-null String.
fun fail(message: String): Nothing {
throw IllegalStateException(message)
}
fun main() {
val loggedInUser: String? = "asha"
val user = loggedInUser ?: fail("Not logged in")
println("User: $user")
val guest: String? = null
val name = guest ?: fail("Session expired, please log in")
println("Never printed: $name")
}Output
User: asha Exception: java.lang.IllegalStateException: Session expired, please log in
Unit vs Nothing vs void
| Type | Meaning | Example |
|---|---|---|
Unit | function finishes, returns no useful value | fun log(msg: String) |
Nothing | function never finishes normally | fun fail(msg: String): Nothing, TODO() |
Java void | no return value (not a type you can store) | void log(String msg) |