问题
I am learning Scala and am a bit confounded by the difference between next types: 'Null', 'Nil' and 'Nothing'.
Can someone please help explain the difference to me? From what i gather, "Nil" is used to describe an empty list.
回答1:
Nothingness in Scala
There are 7 cases where you want to represent the concept of nothingness in Scala.
Nil
- Used for representing empty lists, or collections of zero length. For sets you can use Set.empty
None
- One of two subclasses of the Optional type, the other being Some
. Very well supported by the Scala collections.
Unit
- Equivalent to Java's void
which is used for functions that don't have a return type
Nothing
- A trait. It is a subtype of all other types, but supertype of nothing. It is like the leaf of a tree. No instances of Nothing.
Null
- A trait. Not recommended to be used.
null
- An instance of the trait, similarly used as the Java Null
. Not recommended to be used.
Best Practices
- If you have code that is returning null, change it to return an Optional.
- If you need to have an uninitialized variable, using Optional, or an empty list/collection instead of null *
For best practices recommendation, please see https://alvinalexander.com/scala/scala-null-values-option-uninitialized-variables
Why is null so hated?
- Please watch Tony Hoare's Billion Dollar Mistake
- Null pointer errors are hard to debug
回答2:
In scala null
is realy bad, you must use Optional[T]
.
We have Nil
which is a empty list to be able to do 1 :: Nil
to create a list that contain only 1
.
And, Nothing
is a subtype of every type. In other world, is a object that represent null
.
来源:https://stackoverflow.com/questions/46796032/what-is-difference-between-null-nil-and-nothing