Updated:
Unit is the return type of a Kotlin function that doesn’t return anything useful – Kotlin’s version of Java’s void. Unlike void, Unit is a real type with exactly one value, also called Unit, which makes it work with generics and lambdas.
fun printSum(a: Int, b: Int): Unit {
println(a + b)
}
// ": Unit" and "return Unit" are optional
fun printSum2(a: Int, b: Int) {
println(a + b)
}Unit vs void vs Nothing
| Unit | Java void | Nothing | |
|---|---|---|---|
| Is a type with a value? | Yes, one value: Unit | No | No value at all |
| Meaning | Function finishes, returns no useful value | Same | Function never finishes normally (throws or loops) |
| Usable in generics | Yes: List<Unit>, () -> Unit | No (Java uses Void) | Yes, as a subtype of every type |
Unit in lambdas and callbacks
Function types that return nothing are written with Unit:
fun downloadFile(url: String, onDone: () -> Unit) {
// ... download
onDone()
}
downloadFile("https://example.com/a.pdf") {
println("Downloaded")
}
// Callback with a parameter
fun fetchUser(onResult: (User) -> Unit) { /* ... */ }In a () -> Unit lambda, the value of the last expression is ignored, so you don’t have to return anything.
Unit with generics
Because Unit is a real type, you can use it where a generic type is required but you have no value to give:
sealed interface Result<out T> {
data class Success<T>(val data: T) : Result<T>
data class Error(val message: String) : Result<Nothing>
}
fun deleteItem(id: Int): Result<Unit> =
if (id > 0) Result.Success(Unit) else Result.Error("Bad id")In Java you’d need Void and return null; in Kotlin you return Unit.
Nothing: the function never returns
fun fail(message: String): Nothing = throw IllegalArgumentException(message)
fun parseAge(text: String): Int =
text.toIntOrNull() ?: fail("Not a number: $text")Common mistakes
- Writing
fun f() = println("hi")is fine – it returnsUnit, becauseprintlndoes. val x = doWork()on a Unit function givesx == Unit, notnull.- Don’t use
Unit?to mean “maybe failed” – useBoolean,Resultor an exception.
FAQ
Is Unit the same as void?
It plays the same role, but Unit is an object you can store, pass and use as a type argument; void isn’t a type in that sense.
Do I need to write : Unit?
No. A block-body function without a declared return type returns Unit automatically.
More Kotlin guides
- Kotlin list to map
- Kotlin function return types
- Kotlin variables: val, var, const, global
- Interfaces in Kotlin
- What is Kotlin?
Keep reading


