检查Scala继承我遇到了误解 代码是:
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
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: _*))
}
val l1 = List(1.0, 2.0, 3.0)
println(product(l1))
据我所知,List[+A]
和Cons[+A]
之间的关系是List[+A]
是超级“类”,Cons[+A]
是List[+A]
的子类。
l1
是Con[+A]
的实例
l1
传递给product
方法,其中输入参数ds
的类型List
对其子类Cons
一无所知。
所以问题是如何解释子类对象到超类对象的分配?
答案 0 :(得分:0)
Cons
中的其他方法只有在将其分配给List
类型变量时才会隐藏。所有Animal
都可以移动(大概),但Cow
extends Animal
也可以移动牛奶。如果将类型为Cow
的对象分配给Animal
类型的变量,则只能调用.move
,而不能调用.give_milk
。尽管如此,它仍然是Cow
。