Scala中涉及抽象类型时没有动态绑定吗? [英] No dynamic binding when abstract type involved in Scala?
问题描述
当我在Martin Odersky的 Scala编程中尝试抽象类型的Animal/Food示例时,
When I was trying the Animal/Food example for abstract types in Martin Odersky's Programming in Scala,
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
为Cow
而不是Animal
:val bessy:Cow = new Cow
可以避免上述错误.
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. The above error can be avoided by letting bessy
be Cow
instead of Animal
: val bessy:Cow = new Cow
.
这是否意味着动态绑定在这里不起作用?
Does this mean dynamic binding doesn't work here?
已 在Scala中进行常规继承的简单动态绑定:
Edited: Simple dynamic binding for regular inheritance in 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
推荐答案
Scala是静态类型的.任意动物都不能吃草,而您刚刚尝试将草喂给任意动物.它恰好是一头母牛,但是您已经(使用: Animal
声明)编译器可能仅假设它是动物.
Scala is statically typed. 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.
如果让编译器知道bessy
是Cow
(val bessy = new Cow
),那么她会吃草的.
If you allow the compiler to know that bessy
is a Cow
(val bessy = new Cow
), then she'll eat grass just fine.
这篇关于Scala中涉及抽象类型时没有动态绑定吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!