Consider the following example:
case class Person(name: String, age: Int)
case class Family(surname: String, members: List[Person])
val families = List(
Family("Jones",
List(Person("Indiana", 50), Person("Molly", 20))),
Family("Black",
List(Person("Jack", 55), Person("Derek", 12))))
I want to write a function that finds a person with a certain name in a List[Family] object. This is my current solution:
def find(name: String, families: List[Family]): Option[Person] = {
families.find(f => f.members.exists(m => m.name == name)).map(f => f.members.find(m => m.name == name).get)
}
Is there a more efficient and elegant (and functional) way to achieve this?
families.flatMap(_.members).find(_.name == name)does the job. But your data model appears badly chosen, because there is no way to get the surname ofPerson.