Both types Unit
and Nothing
indicate a function that does not return anything. What's the difference between them?
The semantics of Null are very poorly understood, particularly amongst people who have little experience with programming. Empty says “I'm an uninitialized variant,” Nothing says “I'm an invalid object” and Null says “I represent a value which is not known.” Null is not True, not False, but Null !
You use Unit as a return type in Kotlin when you would use void (lowercase v) in Java. The Nothing type has no values. If a function has return type Nothing , then it cannot return normally. It either has to throw an exception, or enter an infinite loop.
Unit in Kotlin corresponds to the void in Java. Like void, Unit is the return type of any function that does not return any meaningful value, and it is optional to mention the Unit as the return type. But unlike void, Unit is a real class (Singleton) with only one instance.
Unit is a subtype of scala. AnyVal. There is only one value of type Unit , () , and it is not represented by any object in the underlying runtime system. A method with return type Unit is analogous to a Java method which is declared void . Source Unit.scala.
Unit
is a type that has exactly one value ‒ see Unit type. On the other hand, Nothing
has no possible value - see Bottom type.
A function that doesn't return anything must have the return type Unit
. If it were Nothing
then the function could not return a result. The only way to exit the function would be by an exception.
Nothing
is used in a different way. It is characterized by two properties:
Nothing
is a subtype of every other type (including Null
).When is this useful? Consider None
:
object None extends Option[Nothing]
Because Option
is covariant in its type parameter and Nothing
is a subtype of everything, Option[Nothing]
is a subtype of Option[A]
for every type A
. So, we can make one object None
which is a subtype of Option[A]
for every A
. This is reasonable, since Nothing
cannot be instantiated so Option[Nothing]
will always be without a value. Similarly
object Nil extends List[Nothing]
Unit
corresponds to logical true and Nothing
corresponds to logical false under the Curry-Howard isomorphism, where we view types as propositions and functions as proofs, .
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With