scala 中的抽象类型 [英] abstract type in scala
问题描述
我只是在 Scala
中检查抽象类型,但出现错误
I am just going through abstract type in Scala
and I got an error
我尝试的示例:
scala> class Food
abstract class Animal {
type SuitableFood <: Food
def eat(food: SuitableFood)
}
defined class Food
defined class Animal
scala> class Grass extends Food
class Cow extends Animal {
type SuitableFood = Grass
override def eat(food: Grass) {}
}
defined class Grass
defined class Cow
scala> class Fish extends Food
defined class Fish
scala> val bessy: Animal = new Cow
bessy: Animal = Cow@5c404da8
scala> bessy.eat(new bessy.SuitableFood)
<console>:13: error: class type required but bessy.SuitableFood found
bessy.eat(new bessy.SuitableFood)
^
scala> bessy.eat(bessy.SuitableFood)
<console>:13: error: value SuitableFood is not a member of Animal
bessy.eat(bessy.SuitableFood)
scala> bessy.eat(new Grass)
<console>:13: error: type mismatch;
found : Grass
required: bessy.SuitableFood
bessy.eat(new Grass)
这些错误是什么?
为什么我不能将 new Grass
作为参数传递给 eat
方法,当我创建一个像
Why can't I pass new Grass
to the eat
method as an argument, and when I create an object like
scala> val c=new Cow
c: Cow = Cow@645dd660
scala> c.eat(new Grass)
你能给我一些关于这个的想法吗?
Could you give me some idea about this?
推荐答案
当您分配 bessy
时,您将 Cow
实例向上转换为 Anmial
>:
When you assign bessy
, you upcast the Cow
instance to an Anmial
:
val bessy: Animal = new Cow
所以从静态的角度来看,bessy
是一个 Animal
,因此 bessy.SuitableFood
是抽象的.现在来看看错误:
So from a static point of view, bessy
is an Animal
and therefore bessy.SuitableFood
abstract. Now to the errors:
- 您不能使用
new
创建抽象类型的对象. bessy.SuitableFood
尝试访问值成员SuitableFood
(即 def/val)- 因为
bessy
只是"一种Animal
,你不知道(静态地)它是否可以吃草
.
- You cannot create an object of an abstract type with
new
. bessy.SuitableFood
tries to access the value-memberSuitableFood
(i.e. def/val)- Since
bessy
is "only" anAnimal
, you don't know (statically) if it can eatGrass
.
你能做的,就是给Animal
添加一个方法,让你可以创造食物:
What you can do, is add a method to Animal
that allows you to create food:
abstract class Animal {
type SuitableFood <: Food
def eat(food: SuitableFood)
def makeFood(): SuitableFood
}
并实施:
class Cow extends Animal {
type SuitableFood = Grass
override def eat(food: Grass) {}
override def makeFood() = new Grass()
}
现在你可以调用(在任何Animal
上):
Now you may call (on any Animal
):
bessy.eat(bessy.makeFood())
这篇关于scala 中的抽象类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!