Scala子类对象为超类对象赋值

时间:2017-01-07 22:11:14

标签: scala subclass

检查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]的子类。

l1Con[+A]的实例 l1传递给product方法,其中输入参数ds的类型List对其子类Cons一无所知。

所以问题是如何解释子类对象到超类对象的分配?

1 个答案:

答案 0 :(得分:0)

Cons中的其他方法只有在将其分配给List类型变量时才会隐藏。所有Animal都可以移动(大概),但Cow extends Animal也可以移动牛奶。如果将类型为Cow的对象分配给Animal类型的变量,则只能调用.move,而不能调用.give_milk。尽管如此,它仍然是Cow