Concept Flow - Unit type as void equivalent
Call function
Function runs
Returns Unit
Continue execution
When a Kotlin function returns Unit, it means it returns no meaningful value, similar to void in other languages.
fun greet(name: String): Unit { println("Hello, $name!") } greet("Alice")
| Step | Action | Function Return | Output |
|---|---|---|---|
| 1 | Call greet("Alice") | Unit (implicit) | |
| 2 | Execute println inside greet | Unit (implicit) | Hello, Alice! |
| 3 | greet returns Unit | Unit (implicit) | |
| 4 | Continue after greet call | Unit (implicit) |
| Variable | Start | After greet call | Final |
|---|---|---|---|
| name | undefined | "Alice" | "Alice" |
Kotlin functions returning no value use Unit type. Unit is like void in other languages. Functions return Unit implicitly if no return value. You can declare : Unit explicitly or omit it. Unit has a single value: Unit. Useful for functions that perform actions only.
Unit type represent in Kotlin?UnitUnit in Kotlin means the function does not return any meaningful value, similar to void in other languages.Unit.Unit = no meaningful return [OK]Unit explicitly in Kotlin?: before the return type, so fun greet(): Unit is correct.-> which is invalid syntax. fun greet(): void { println("Hello") } uses void which is not a Kotlin type. fun greet() { return Unit } tries to return Unit explicitly but misses the return type declaration.fun printMessage(): Unit {
println("Hello, Kotlin!")
}
fun main() {
val result = printMessage()
println(result)
}printMessage returns Unit, which is a singleton object in Kotlin representing no meaningful value.println(result)result, which is Unit, Kotlin prints "kotlin.Unit" as its string representation.fun show(): Unit {
return
println("Hi")
}return statement ends the function immediately, so the println("Hi") after it is unreachable code.println statement is unreachable after return -> Option CUnit is the equivalent of void and can be omitted because it is the default return type for functions without a meaningful return.Unit return type and omitting the return statement is clear and idiomatic. Using return Unit or return without value is allowed but less common. void is invalid in Kotlin.Unit explicitly and omit the return statement -> Option DPass the test and this pattern moves unknown