Kotlin: Void, Unit and Nothing — what's the difference and when to use what?
Hello everyone! I recently started learning Kotlin and switched from Java. In Java, I'm used to void for methods that return nothing. But in Kotlin, I see three similar concepts: Void, Unit, and Nothing. And I'm confused.
For example, I write a function that simply prints a greeting:
fun greet(name: String) {
println("Hello, $name!")
}
The compiler says the return type is Unit. But I can also write it like this:
fun greet(name: String): Unit {
println("Hello, $name!")
}
Also, I've seen Void (capitalized) and Nothing in someone else's code. When I tried to use Nothing as a return type, the compiler said the function never completes normally.
Please explain:
- How are
Unit,Void, andNothingdifferent? - When should I use