When a function doesn’t return a useful value, the compiler assigns a return type of Unit
. This is a special type that has exactly one value (confusingly also called Unit
).
However, there’s another predefined type with exactly one value: Nothing?
, with the value null
.
Why was that not chosen for such functions instead?
It would probably be more intuitive to receive the value null
(judging from the questions I see asking what this Unit
is all about), and it would avoid an extra predefined type. (Unit brings other redundancies, too: for example, not only is Unit
isomorphic to Nothing?
, but Unit?
is a type with two possible values, isomorphic to Boolean
.)
I’m guessing one of the reasons is historical: functional languages generally have such a type, though I think it’s only called ‘unit’ in ML descendants (OCaml, Standard ML, F#), and Scala. However many others call it ‘null’ (or ‘nil’): Common Lisp, PHP, JavaScript, Ruby — so there’s precedent both ways.
Another possible reason could be complications from Nothing?
being a subtype of all nullable types — but I can’t think of any.
Did Kotlin simply take it from Scala, without considering that Kotlin’s expressive type system already provided an alternative? Or is there some benefit to having both?