```
sealed trait List[+A] // `List` data type, parameterized on a type, `A`
case object Nil extends List[Nothing] // A `List` data constructor representing the empty list
/* Another data constructor, representing nonempty lists. Note that `tail` is another `List[A]`,
which may be `Nil` or another `Cons`.
*/
case class Cons[+A](head: A, tail: List[A]) extends List[A]
object List { // `List` companion object. Contains functions for creating and working with lists.
def sum(ints: List[Int]): Int = ints match { // A function that uses pattern matching to add up a list of integers
case Nil => 0 // The sum of the empty list is 0.
case Cons(x, xs) => x + sum(xs) // The sum of a list starting with `x` is `x` plus the sum of the rest of the list.
}
def product(ds: List[Double]): Double = ds match {
case Nil => 1.0
case Cons(0.0, _) => 0.0
case Cons(x, xs) => x * product(xs)
}
def apply[A](as: A*): List[A] = // Variadic function syntax
if (as.isEmpty) Nil
else Cons(as.head, apply(as.tail: _*))
...
```
关于型变(variance)
在trait List[+A]声明里,类型参数A前边的+是一个型变的符号,标志着A是协变的或正向(positive)的参数。意味着假设Dog是Animal的子类,那么List[Dog]是List[Animal]的子类。(多数情况下,所有类型X和Y,如果X是Y的子类型,那么List[X]是List[Y]的子类型)。我们可以在A的前面去掉+号,那样会标记List的参数类型是非型变的(invariant)。但注意Nil继承List[Nothing],Nothing是所有类型的子类型,也就是说使用型变符号后Nil可以当成是List[Int]或List[Double]等任何List的具体类型。
233
来源:oschina
链接:https://my.oschina.net/lemos/blog/4333290