Is there a method to do the following without doing both methods: find
and map
?
val l = 0 to 3
l.find(_ * 33 % 2 == 0).map(_ * 33) //
Hey look, it's my little buddy findMap
again!
/**
* Finds the first element in the list that satisfies the partial function, then
* maps it through the function.
*/
def findMap[A,B](in: Traversable[A])(f: PartialFunction[A,B]): Option[B] = {
in.find(f.isDefinedAt(_)).map(f(_))
}
Note that, unlike in the accepted answer, but like the collectFirst
method mentioned in one of its comments, this guy stops as soon as he finds a matching element.