当我在 Martin Odersky 的Programming in Scala中尝试抽象类型的 Animal/Food 示例时,
class Food
abstract class Animal {
type SuitableFood <: Food
def eat(food:SuitableFood)
}
class Grass extends Food
class Cow extends Animal {
type SuitableFood=Grass
override def eat(food:SuitableFood) {}
}
val bessy:Animal = new Cow
bessy.eat(new Grass)
我收到以下错误:
scala> <console>:13: error: type mismatch;
found : Grass
required: bessy.SuitableFood
bessy.eat(new Grass)
^
Martin 的原始示例是bessy.eat(new Fish)
,它肯定会失败,但我没想到它也会失败Grass
。bessy
可以通过让beCow
代替Animal
:来避免上述错误val bessy:Cow = new Cow
。
这是否意味着动态绑定在这里不起作用?
编辑: Scala中常规继承的简单动态绑定:
abstract class Parent {
def sig:String = "Parent"
}
class Child extends Parent {
override def sig:String = "Child"
}
我有这个,x:Parent
也给了Child:
scala> new Child().sig
res1: String = Child
val x:Parent = new Child()
x: Parent = Child@3a460b07
x.sig
res2: String = Child