【问题标题】:No dynamic binding when abstract type involved in Scala?Scala中涉及抽象类型时没有动态绑定?
【发布时间】:2013-12-24 02:39:00
【问题描述】:

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

Martin 的原始示例是bessy.eat(new Fish),它肯定会失败,但我没想到Grass 也会失败。通过让bessyCow 而不是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 也给了孩子

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

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

x.sig
res2: String = Child

【问题讨论】:

    标签: scala dynamic-binding abstract-type


    【解决方案1】:

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

    如果您允许编译器知道bessyCow (val bessy = new Cow),那么她会吃草就好了。

    【讨论】:

    • 好吧,我是不是把动态绑定的概念弄错了? Java 中的ListLinkedListArrayList,所以当你在List 上调用xs.get(idx) 时,你会得到ArrayList 版本,而它是ArrayList 实现。我没想到 Scala 会偏离这一点。
    • @lcn - 类型必须匹配。您的“简单”示例对Parent.sigChild.sig 具有相同的类型签名。继承(C++ 中的“动态绑定”类型)工作得很好,但你必须遵守你给定的类型。
    • 所以你的意思是当涉及抽象类型时,eat 方法将具有 不同 签名,因此是不同的方法?我知道这更适合抽象类型的目的,但确实应该记录一下这里有 NO 动态绑定。
    • @lcn - 它是运行时的动态绑定(因为该术语在 C++ 中使用;这在其他上下文中意味着不同的事物),因为从方法表中选择了适当的方法。但是,在编译时,编译器会阻止您将草喂给任意动物。
    猜你喜欢
    • 2017-01-30
    • 2011-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-12
    • 2011-12-27
    相关资源
    最近更新 更多