What's the difference between Unit and Nothing?
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 (includingNull
).- There exist no instances of this type.
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, .
Unit
means that (a) function has side effects like input and output, (b) these side effects are the main goal of the function. Of course, a function can have side effects even if its type is different from Unit
.
Nothing
is a special type in Scala, because (a) it has no values (Unit has exactly one value - ()
), so you cannot return a value of type Nothing
, and (b) it is a subtype of every other type. That means that if something has the type Nothing
, it can be used instead of any other type (via subtyping), but it won't produce any result. This is useful for dealing with exceptions - the throw
expression has a type of Nothing
, so it can be used everywhere in a program.
Simply, Nothing
means that there was an error or termination of a program and nothing was returned, while Unit
means there were side effects, but execution ended normally with no result.
Programming in Scala has a nice explanation of that.
To add one aspect to Petr's reply: Nothing
plays an important role in the type hierarchy. It is a bottom type. That means that it is a subtype of every other type, which is like the opposite of Any
, which is a supertype of everything. You can find a nice explanation here.