Scala子类对象到超类对象的赋值
检查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]
代码是:
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
的typeList
对其子类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
类型变量时,它就会变得隐藏。所有的动物smove
(大概),但是cow
也产奶。如果将类型为cow
的对象指定给类型为animal
的变量,则只能调用.move
,而不能调用.give_milk
。不过里面还是一头奶牛。