Suppose there is a trait for legged animals:
trait Legged {
val legs: Int
def updateLegs(legs: Int): Legged
}
And there two such legged animals:
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)
}
There is also a holder for these animal, in a farm
case class Farm(chicken: Chicken, dog: Dog)
And a generic method to mutate all the legged animals by adding them one extra leg
def mutate(legged: Legged): Legged = legged.updateLegs(legged.legs + 1)
The question is how to implement a method on the Farm
so that it takes the mutate: Legged => Legged
function as a parameter and applies it to all the Legged
animals?
val farm = Farm(Chicken(1500), Dog("Max"))
farm.mapAll(mutate) //this should return a farm whose animals have an extra leg
What I've come with thus far, but it doesn't actually work
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)
}
}
I know how to do it with patter matching, but that leads to potential MatchError
.