[ACCEPTED]-How to find a matching element in a list and map it in as an Scala API method?-scala-2.8

Accepted answer
Score: 32

How about using collect?

// Returns List(66)
List(1, 2, 3) collect { case i if (i * 33 % 2 == 0) => i * 33 }

However that will 9 return all matches and not just the first one.

The 8 better answer would have been, based on 7 Scala 2.9:

// Returns Some(66)
List(1, 2, 3) collectFirst { case i if (i * 33 % 2 == 0) => i * 33 }

The solution suggested in the 6 comments to append a head to get a Scala 2.8 5 version of that is not very efficient, I'm 4 afraid. Perhaps in that case I would stick 3 to your own code. In any case, in order 2 to make sure it returns an option, you should 1 not call head, but headOption.

// Returns Some(66)
List(1, 2, 3) collect { case i if (i * 33 % 2 == 0) => i * 33 } headOption
Score: 22

If you don't want to do your map() operation 4 multiple times (for instance if it's an 3 expensive DB lookup) you can do this:

l.view.map(_ * 33).find(_ % 2 == 0)

The 2 view makes the collection lazy, so the number 1 of map() operations is minimized.

Score: 6

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 4 that, unlike in the accepted answer, but 3 like the collectFirst method mentioned in one of its 2 comments, this guy stops as soon as he finds 1 a matching element.

More Related questions