首页 文章

Scala中涉及抽象类型时没有动态绑定?

提问于
浏览
1

当我在Martin Odersky的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)
                            ^

马丁的原始例子是 bessy.eat(new Fish) ,这肯定会失败,但我也没有't expect it'失败 Grass . 通过让 bessyCow 而不是 Animalval bessy:Cow = new Cow 可以避免上述错误 .

这是否意味着动态绑定在这里不起作用?

Edited: Scala中常规继承的简单动态绑定:

abstract class Parent {
  def sig:String = "Parent"
}
class Child extends Parent {
  override def sig:String = "Child"
}

我有这个, x:Parent 给了孩子:

scala> new Child().sig
res1: String = Child

val x:Parent = new Child()
x: Parent = Child@3a460b07

x.sig
res2: String = Child

1 回答

  • 6

    Scala是静态类型的 . 任意动物都不能吃草,而你刚刚尝试将草喂给任意动物 . 它碰巧是一头牛,但你已经声明(使用 : Animal )编译器可能只假设它是动物 .

    如果你允许编译器知道 bessyCowval bessy = new Cow ),那么她会吃草就好了 .

相关问题