Safe way to operate on a sequence filter

  Kiến thức lập trình

THe intention in the code below is to get the name of the student whose id is equal to 30

class Person(name: String ,  id : Int)
val people = Seq(
    Person("Emily", 10),
    Person("Hannah", 20),
    Person("Mercedes", 30)
)
val selected = people.filter(_.id == 30).headOption.map(_.name).get

While this code would work – it has main points of failure.
What is the recommended way to write this safe and clean.

LEAVE A COMMENT