One of the meanings: used for type parameters (covariant parameterized types).
First, Scala's generics are not allowed without type parameters. The following is excerpted from programming in Scala, 2nd Edition, Chapter Type Parameterization
Unlike Java, which allows raw types, Scala requires that you specify type parameters.
(Do not allow raw type,scala like Java to specify type parameters)
So the following two rows are faulted: Error:type List takes type parameters
Listval li: List = List(1)
Rewrite it as follows to compile:
List[String]val li: List[Int] = List(1)
Because the list (1) has an element of type Int: 1, so his type is list[int]. Well, make sense, the type of a list depends on the elements in the list. So list ("abc") is the list[string type, list ("abc", 1) is List[any], because "ABC" and 1 are all subtypes of any type. This is how type deduction works.
So what about list ()? An empty list, what type is he? Certainly not List[int], because there is no Int, nor List[any], because there is nothing, there is no reason to push the export of any other type, so this list () can only be list[nothing].
List()l: List[Nothing] = List()
Nil is inherited from list[nothing]. So can do 1:: Nil and "abc":: Nil. Also because Nil is list[nothing],nothing is Bottome type,list is covariant, so 1:: Nill will be deduced into List[int], "abc":: Nil will be deduced into list[string]
case object Nil extends List[Nothing] { override def isEmpty = true def head: Nothing = throw new NoSuchElementException("head of empty list") def tail: List[Nothing] = throw new NoSuchElementException("tail of empty list")}
Small experiment, can you compile and execute it? What is the type of ML1?
val ml: List[String] = List()val ml1 = 2 :: ml
meaning of the second, representing the abnormal exit. like throwing exceptions. This is also very made sense, abnormal, certainly nothing will return, type only is nothing.
throw new Exception("s")e: Nothing
The nil head method above is also an example. This also shows the benefits of the bottom type of nothing.
Boolean) = if(p) 1 else throw new Exception("yeah")er: (p: Boolean)Int
Type derivation observes the following procedure and finds that there are 2 possible return types for this ER method, one is int and the other is nothing. Since nothing is a bottom type, the null is a subclass of int, so it is considered that the 2 types that may be returned are int, so the return value of the ER method is deduced as int.