Both types Unit and Nothing indicate a function that does not return anything. What’s the difference between them?
Both types Unit and Nothing indicate a function that does not return anything. What’s
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Unitis a type that has exactly one value ‒ see Unit type. On the other hand,Nothinghas no possible value – see Bottom type.A function that doesn’t return anything must have the return type
Unit. If it wereNothingthen the function could not return a result. The only way to exit the function would be by an exception.Nothingis used in a different way. It is characterized by two properties:Nothingis a subtype of every other type (includingNull).When is this useful? Consider
None:Because
Optionis covariant in its type parameter andNothingis a subtype of everything,Option[Nothing]is a subtype ofOption[A]for every typeA. So, we can make one objectNonewhich is a subtype ofOption[A]for everyA. This is reasonable, sinceNothingcannot be instantiated soOption[Nothing]will always be without a value. SimilarlyUnitcorresponds to logical true andNothingcorresponds to logical false under the Curry-Howard isomorphism, where we view types as propositions and functions as proofs, .