建议使用scala抽象类型进行练习

建议使用scala抽象类型进行练习,scala,abstract-type,Scala,Abstract Type,我正在寻找关于我正在做的这个练习的建议-具体来说,哪些方面可以改进/缩短?我不喜欢用它来喂动物,我不得不用来代替,但找不到更好的方法。我的想法是,我需要为数百万个对象运行此函数,因此性能非常重要 顺便问一下,在我的情况下,仿制药的表现会更好吗 trait Animal { type suitableFood def eat(f: suitableFood) } trait Food case class Grass (val color: String) extends Food cas

我正在寻找关于我正在做的这个练习的建议-具体来说,哪些方面可以改进/缩短?我不喜欢用它来喂动物,我不得不用来代替,但找不到更好的方法。我的想法是,我需要为数百万个对象运行此函数,因此性能非常重要

顺便问一下,在我的情况下,仿制药的表现会更好吗

trait Animal {
  type suitableFood
  def eat(f: suitableFood)
}
trait Food
case class Grass (val color: String) extends Food
case class Fish (val size: String, val condition: String) extends Food

trait GrassT{
  type suitableFood = Grass
}
trait FishT{
  type suitableFood = Fish
}
class Cow extends Animal with GrassT{
  def eat (f: suitableFood) = {
    println("moo " + f.color)
  }
}
class Sheep extends Animal with GrassT{
  def eat (f: suitableFood) = {
    println("baaa " + f.color)
  }
}
class Cat extends Animal with FishT{
  def eat (f: suitableFood) = {
    println("mew " + f.size + " " + f.condition)
  }
}
val cow = new Cow
val sheep = new Sheep
val whiteCat = new Cat
val blackCat = new Cat
val fish = new Fish("small", "fresh")
val grass = new Grass("green")
val cats = List(whiteCat, blackCat)
val farmAnimals = List(sheep, cow)
def feedAnimals[F <: Food](food: F, animals: List[Animal]) = {
  animals.foreach(a => a.eat(food.asInstanceOf[a.suitableFood]))
}
feedAnimals(grass, farmAnimals)
feedAnimals(fish, cats)
trait动物{
类型适宜食品
def eat(f:适宜食品)
}
特色食品
案例类草(val颜色:String)扩展食物
案例类鱼(val大小:String,val条件:String)扩展食物
性状格拉斯特{
适合的食物类型=草
}
特征鱼{
适合的食物类型=鱼
}
第二类用草喂养动物{
def eat(f:适宜食品)={
println(“moo”+f.color)
}
}
第二类羊用草喂养动物{
def eat(f:适宜食品)={
println(“baaa”+f.color)
}
}
猫类动物与鱼{
def eat(f:适宜食品)={
println(“mew”+f.size+“”+f.condition)
}
}
瓦尔牛=新牛
瓦尔羊=新羊
瓦尔·怀特卡特=新猫
瓦尔黑猫=新猫
瓦尔鱼=新鱼(“小”、“新鲜”)
val grass=新草(“绿色”)
val cats=列表(白猫、黑猫)
val农场动物=列表(绵羊、奶牛)
def饲养动物[F a.吃(食物)代替[a.适宜食物])
}
饲养动物(草、家畜)
饲养动物(鱼、猫)

您只需对饲养动物设置更严格的类型限制即可:

def feedAnimals[F <: Food](food: F, animals: List[Animal { type suitableFood = F }]) = 
    animals.foreach(_.eat(food))

def feedanies[F谢谢,这正是我想要的!
def feedAnimals[F <: Food, A <: Animal { type suitableFood = F }](food: F, animals: List[A]) = 
    animals.foreach(_.eat(food))