Unit in Kotlin: Unit vs Void vs Nothing (with Examples)

Kotlin course · Functions · Lesson 21 of 51

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

UnitJava voidNothing
Is a type with a value?Yes, one value: UnitNoNo value at all
MeaningFunction finishes, returns no useful valueSameFunction never finishes normally (throws or loops)
Usable in genericsYes: List<Unit>, () -> UnitNo (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 returns Unit, because println does.
  • val x = doWork() on a Unit function gives x == Unit, not null.
  • Don’t use Unit? to mean “maybe failed” – use Boolean, Result or 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

WhatsApp us📞 Call now