简体   繁体   English

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

[英]No dynamic binding when abstract type involved in Scala?

When I was trying the Animal/Food example for abstract types in Martin Odersky's Programming in Scala , 当我在Martin Odersky 在ScalaProgramming中尝试抽象类型的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)

I got the following error: 我收到以下错误:

scala> <console>:13: error: type mismatch;
 found   : Grass
 required: bessy.SuitableFood
                  bessy.eat(new Grass)
                            ^

The original example by Martin was bessy.eat(new Fish) , which would definitely fail, but I didn't expect it'd fail for Grass as well. 马丁最初的例子是bessy.eat(new Fish) ,它肯定会失败,但是我没想到Grass也会失败。 The above error can be avoided by letting bessy be Cow instead of Animal : val bessy:Cow = new Cow . 可以通过将bessy设为Cow而不是Animal来避免上述错误: val bessy:Cow = new Cow

Does this mean dynamic binding doesn't work here? 这是否意味着动态绑定在这里不起作用?

Edited: Simple dynamic binding for regular inheritance in Scala: 编辑: Scala中用于常规继承的简单动态绑定:

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

And I had this, where x:Parent gave Child as well: 我有这个, x:Parent给了Child

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

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

x.sig
res2: String = Child

Scala is statically typed. Scala是静态类型的。 An arbitrary animal cannot eat grass, and you have just tried to feed grass to an arbitrary animal. 任意动物都不能吃草,而您只是试图将草喂给任意动物。 It happens to be a cow, but you have stated (with : Animal ) that the compiler may only assume that it is an animal. 它碰巧是一头牛,但是您已经(使用: Animal )声明过,编译器可能仅假设它是动物。

If you allow the compiler to know that bessy is a Cow ( val bessy = new Cow ), then she'll eat grass just fine. 如果让编译器知道bessy是一头Cowval bessy = new Cow ),那么她会吃草的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM