Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between Unit and Nothing?

Tags:

scala

Both types Unit and Nothing indicate a function that does not return anything. What's the difference between them?

like image 621
Reactormonk Avatar asked Nov 24 '12 09:11

Reactormonk


People also ask

What is difference between Null and nothing?

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 !

What is any Unit and nothing in Kotlin?

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.

What is a Unit in Kotlin?

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.

What is Unit in Scala?

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.


1 Answers

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:

  1. Nothing is a subtype of every other type (including Null).
  2. 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, .

like image 104
Petr Avatar answered Oct 27 '22 22:10

Petr