collectFirst will first call isDefinedAt to determine if apply should be called for the current item in the list. Thus it will skip over the non matching elements in the list without incurring a match exception.
trait Animal
case class Mammal(name: String) extends Animal
case class Bird(name: String) extends Animal
val animals = Seq(Mammal("elephant"), Mammal("tiger"), Bird("raven"), Mammal("monkey"), Bird("peacock"), Bird("sparrow"))
val matchBird = new PartialFunction[Animal, Bird] {
def apply(p: Animal) = {
p match {
case b@Bird(name) => b
}
}
def isDefinedAt(p: Animal) = {
p match {
case Bird(name) => true
case _ => false
}
}
}
animals collectFirst matchBird
res11: Option[Bird] = Some(Bird(raven))
No comments:
Post a Comment