【发布时间】:2023-03-08 15:17:01
【问题描述】:
我正在尝试传递 Grass 或 Rice 对象。但是,它编译失败。我根据此链接using Either 尝试了以下Either[] 选项。但是,它不起作用。
我想像这样限制传递 Fish 对象。我只想通过Rice 或Grass。
(new Cow).eat(new Fish) // I don't want this to happen
请告诉我为什么Either 在这里不起作用。
object AbstractType {
def main(args: Array[String]): Unit = {
(new Cow).eat(new Grass) // Error here -- type mismatch; found : Grass required: scala.util.Either[Grass,Rice]
}
}
abstract class Animal{
type FoodType <: Food
def eat(food : FoodType)
}
class Food{}
class Grass extends Food
class Rice extends Food
class Fish extends Food{}
class Cow extends Animal{
type FoodType = Either[Grass,Rice] // instead of Either[], keeping Grass here is compiling successfully as expected.
def eat(food : FoodType) {
println("Cow eats")
}
}
我按照slouc 的建议尝试了以下方法。但是,即使这种方法也无法限制这一点。 (new Cow).eat(Fish())。
object AbstractType {
def main(args: Array[String]): Unit = {
(new Cow).eat(Grass())
}
}
abstract class Animal{
type FoodType <: Food
def eat(food : FoodType)
}
sealed trait Food
final case class Grass() extends Food
final case class Rice() extends Food
final case class Fish() extends Food
class Cow extends Animal{
type FoodType = //fill here
def eat(food : FoodType) {
println("Cow eats")
}
}
我的问题:填写上述代码的更好方法是什么,以便我只能传递 Rice 或 Grass 对象。(如果没有,如何实现其他方式)并限制 @987654335 @对象。
【问题讨论】:
标签: scala