Part 05 / Topic 3 of 8
Unit: nothing meaningful to return
A function with no return type -- farewell and isPrime's cousins that only println -- is
shorthand for returning Unit, a real type with exactly one possible value, also called
Unit. This isn't Java's void, which isn't a type at all and can't be stored in anything; Unit
behaves like any other value, it's just a value that carries no information.
fun printBanner(shopName: String): Unit {
println("Welcome to $shopName")
}
fun printBannerIdiomatic(shopName: String) { // ": Unit" omitted -- identical meaning
println("Welcome to $shopName")
}
fun main() {
val x = printBanner("Saral Mart")
println(x) // the function's own return value
println(x == Unit) // there is only ever one Unit value
printBannerIdiomatic("Encore Books")
}
Welcome to Saral Mart
kotlin.Unit
true
Welcome to Encore Books
printBanner and printBannerIdiomatic mean exactly the same thing; writing : Unit is legal
but nobody does it in real code -- every function you write without an explicit return type
(farewell, section 1) is quietly returning Unit already.
Full program: examples/03_unit_return_type.kt.
Done here? The practice set for Part 5 — including the solutions — is on the part page.