Scala subclass 对象到 super class 对象赋值
Scala subclass object to super class object assignment
考察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]
是超级"class",Cons[+A]
是次class List[+A]
个。
l1
是 Con[+A]
.
的实例
l1
被传递给 product
方法,其中输入参数 ds
的类型 List
对其子 class Cons
一无所知。
所以问题是如何解释子class对象到超级class对象的赋值?
Cons
中的其他方法在您将其分配给 List
类型变量时简单地隐藏起来。所有 Animal
都可以移动(大概),但是 Cow
其中 extends Animal
也会产生牛奶。如果将Cow
类型的对象赋值给Animal
类型的变量,则只能调用.move
,不能调用.give_milk
。不过里面还是Cow
。
考察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]
是超级"class",Cons[+A]
是次class List[+A]
个。
l1
是 Con[+A]
.
的实例
l1
被传递给 product
方法,其中输入参数 ds
的类型 List
对其子 class Cons
一无所知。
所以问题是如何解释子class对象到超级class对象的赋值?
Cons
中的其他方法在您将其分配给 List
类型变量时简单地隐藏起来。所有 Animal
都可以移动(大概),但是 Cow
其中 extends Animal
也会产生牛奶。如果将Cow
类型的对象赋值给Animal
类型的变量,则只能调用.move
,不能调用.give_milk
。不过里面还是Cow
。