意義之一:用於型別參數(covariant parameterized types)。
首先,Scala的泛型是不允許不加型別參數的。 以下摘自Programming In Scala, 2nd Edition, Chapter 19 Type Parameterization
Unlike Java, which allows raw types, Scala requires that you specify type parameters.
(不像Java那樣允許raw type,Scala必須指定型別參數)
所以以下兩行會出錯:Error: type List takes type parameters
type myList = Listval li: List = List(1)
改寫成如下可以通過編譯:
type myList = List[String]val li: List[Int] = List(1)
因為List(1)有一個Int型的元素:1,所以他的類型是List[Int]。嗯,make sense,一個List的類型取決於這個List裡面的元素。所以List(“abc”)那麼就是List[String]型,List(“abc”, 1)就是List[Any],因為"abc"和1都是Any型的子類型。類型推導就是這麼工作的。
那麼List()呢?一個空的List,他是什麼類型呢?肯定不是List[Int],因為裡面並沒有Int,也不是List[Any],因為裡面啥都沒有,沒有理由推匯出任何一個其他類型,於是這個List()只能是List[Nothing]。
scala> val l = List()l: List[Nothing] = List()
Nil就是繼承自List[Nothing]的。所以才可以做1 :: Nil和"abc” :: Nil。也正因為Nil是List[Nothing],Nothing是bottome type,List是協變的,所以1 :: Nill才會被推導成List[Int],“abc” :: Nil會被推導成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")}
小實驗,下面可以編譯執行嗎?ml1的類型是什麼呢?
val ml: List[String] = List()val ml1 = 2 :: ml
意義之二,代表非正常退出。比如拋異常。這個也很make sense,異常嘛,肯定啥都返回不了,類型只有是Nothing了。
scala> def e = throw new Exception("s")e: Nothing
上文中的Nil的head方法也是一個例子。這裡也體現了Nothing的Bottom Type的好處。
scala> def er(p: Boolean) = if(p) 1 else throw new Exception("yeah")er: (p: Boolean)Int
類型推導觀察了下程式,發現這個er方法有2種可能的傳回型別,一種是Int,一種是Nothing。由於Nothing是Bottom Type,所以Nothing是Int的子類,所以認為這2種可能返回的類型都是Int,所以推匯出er方法的傳回值是Int。