假设有腿动物有一个特征:
trait Legged {
val legs: Int
def updateLegs(legs: Int): Legged
}
还有两种这样的有腿动物:
case class Chicken(feathers: Int, legs: Int = 2) extends Legged {
override def updateLegs(legs: Int): Legged = copy(legs = legs)
}
case class Dog(name: String, legs: Int = 4) extends Legged {
override def updateLegs(legs: Int): Legged = copy(legs = legs)
}
在农场里也有这些动物的持有人
case class Farm(chicken: Chicken, dog: Dog)
还有一种通用方法,通过添加一条额外的腿来变异所有有腿的动物
def mutate(legged: Legged): Legged = legged.updateLegs(legged.legs + 1)
问题是如何实现一个方法,Farm
以便将mutate: Legged => Legged
函数作为参数并将其应用于所有Legged
动物?
val farm = Farm(Chicken(1500), Dog("Max"))
farm.mapAll(mutate) //this should return a farm whose animals have an extra leg
到目前为止我所带来的,但它实际上并没有工作
trait LeggedFunc[T <: Legged] extends (T => T)
case class Farm(chicken: Chicken, dog: Dog) {
def mapAll(leggedFunc: LeggedFunc[Legged]): Farm = {
//todo how to implement?
val c = leggedFunc[Chicken](chicken)
}
}
我知道如何通过模式匹配来做到这一点,但这会导致潜在的MatchError
.