liveBook · Manning

Unit type

As explained in Kotlin in Action, 2E

A unit type is a type with exactly one value, commonly written (), that represents the absence of meaningful information or a meaningful result.

Kotlin’s Unit type represents a function result with no meaningful information. It has exactly one value, also called Unit, and Kotlin returns that value implicitly. A block-bodied function can omit the return type; writing Unit makes the intent explicit. section 8.1.6

Returning Unit

fun logMessage(message: String): Unit { println(message) } fun logMessageBriefly(message: String) { println(message) } Both functions return Unit. In ordinary non-generic functions, Kotlin commonly compiles Unit-returning functions to JVM void methods, preserving familiar Java interoperability. section 8.1.6

Unit differs from Java’s void because it is a full-fledged type and can appear as a type argument. This makes it useful when a generic interface requires a result type but an implementation produces no meaningful result. section 8.1.6

interface Processor<T> {
    fun process(): T
}
 
class NoResultProcessor : Processor<Unit> {
    override fun process() {                  #1
        // do stuff
    }                                         #2
}

Use Unit to implement a result-producing generic interface when processing performs work without returning useful data. section 8.1.6

Function types make Unit especially visible:

  • A regular function may omit Unit because the compiler can infer it. section 8.1.6
  • A function type must state its return type explicitly: () -> Unit. section 10.1.1
  • Do not confuse Unit with Nothing: Unit has one value, whereas Nothing describes functions that do not terminate normally. section 8.1.6 section 8.3

How Kotlin in Action, 2E covers it

How deep it goes
Defines Unit, implicit returns, JVM void compilation, generic type arguments, and explicit function-type syntax.
Examples
Uses Unit-returning functions, a Processor<Unit> implementation, and the () -> Unit function type.
What it assumes
Assumes basic Kotlin functions and generics while reinforcing return types and function-type declarations.
What you can do after
Apply it via Kotlin function declarations and generic interfaces when no meaningful result exists.
How it connects
Connects Unit with void, Nothing, generics, function types, and Java interoperability.

Also explained in

Compare how 7 books explain unit type →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Kotlin in Action, 2E. The section links point to the parts of the book it draws on.