简体   繁体   English

Scala中的类类型参数。

[英]Class type parameters in Scala.

I'm having difficulty writing something that should be quite straight-forward, but I can't seem to get the syntax right. 我写一些应该很直接的东西很难,但我似乎无法正确理解语法。

I have a class hierarchy for foods: 我有食物的类层次结构:

Food :> Vegetable :> Bamboo

And for animals: 而对于动物:

Animal :> Herbivore :> Panda

And I'm trying to define an eat method in Animal, so that Pandas can't eat Vegetables in general, only Bamboo. 而我正试图在动物中定义一种吃法,这样熊猫一般不能吃蔬菜,只能吃竹子。 At the moment, my code looks like this: 目前,我的代码如下所示:

class Food(val name : String)
class Vegetable(name: String) extends Food(name)
class Bamboo extends Vegetable("bamboo")

class Animal[F <: Food](val name : String) {
    def eat[T <: F](f : T) = println(s"$name eats some yummy ${f.name}")
}
class Herbivore[F <: Vegetable](name :String) extends Animal[Vegetable](name)
class Panda extends Herbivore[Bamboo]("panda")

my trouble is, that when I create a Vegetable, the Panda can eat it: 我的麻烦是,当我创造一个蔬菜时,熊猫可以吃它:

(new Panda) eat (new Vegetable("potato"))

So something's going wrong :( 出了点问题:(

Any help would be very welcome :) 任何帮助将非常欢迎:)

You need to change: 你需要改变:

class Herbivore[F <: Vegetable](name :String) extends Animal[Vegetable](name)

to: 至:

class Herbivore[F <: Vegetable](name :String) extends Animal[F](name)

Otherwise you're throwing out the type information by not using F. 否则你不会使用F丢弃类型信息。

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

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