Let's suppose I have a hierarchy like this:
And this is my code:
trait Animal {
def name: String
}
trait Reptile extends Animal {
}
trait Bird extends Animal{
}
trait Mammal extends Animal{
}
case class Snake(name: String) extends Reptile
case class Parrot(name: String, beak: String, wings: String) extends Bird
case class Platypus(name: String, beak: String, fur: String) extends Mammal
case class Cat(name: String, fur: String) extends Mammal
Question is: How can I get every animal in a list of animals that has a certain attribute? For example, I might want to get every instance of animal with fur in my list. I think I could use reflection to iterate over the hierarchy of classes but I want to avoid that. Another possibility would be to add a trait "AnimalWithFur" and then every animal with fur would have to extend it. If I have a Seq[Animal] animals, I could do something like this:
val animalsWithFur:Seq[AnimalWithFur] = animals.collect{case a: AnimalWithFur => a}
but I'd need a new trait for every new characteristic in any animal class (fins, paws, etc.).
This model should escalate, therefore I might add many new animals and features in the future. I also need to keep this hierarchy because I might want to list every Mammal or every Bird. Also I can't simply add "beak" as a feature of birds because platypuses also have beaks.
Aucun commentaire:
Enregistrer un commentaire