Scala子类对象到超类对象的赋值

Scala子类对象到超类对象的赋值,scala,subclass,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]

检查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
的type
List
对其子类
Cons
一无所知


那么问题是如何解释将子类对象分配给超类对象?

当您将子类对象分配给
列表
类型变量时,
Cons
中的其他方法将被隐藏。所有的
动物都可以移动(大概),但是
奶牛也可以产奶。如果将
Cow
类型的对象指定给
Animal
类型的变量,则只能调用
.move
,而不能调用
.give\u milk
。不过,它内部仍然是一个
Cow

s/到超类对象/到超类类型的参数/
。你有OOP方面的经验吗?旁注:
case Cons(0.0,)=>0.0
不符合IEEE-754。一个反例是
0.0*Double.NaN
,它的计算结果是
Double.NaN
@Victor Moroz,我想是的。但我在这里是因为我不清楚具体的例子。到底什么是不清楚的?您有一个类型为
List[Double]
的变量/参数,您可以为它分配/传递类型为
List[Double]
的任何对象或任何子类型,例如
Cons[Double]
,因为
List
是协变的,就像在任何其他OOP语言中一样。或者问题是
product
如何从
List
类型的对象中匹配和提取
Cons
/
Nil
?当您将
Cons
中的附加方法分配给
List
类型变量时,它就会变得隐藏。所有的
动物
s
move
(大概),但是
cow
也产奶。如果将类型为
cow
的对象指定给类型为
animal
的变量,则只能调用
.move
,而不能调用
.give_milk
。不过里面还是一头奶牛。