How to find a matching element in a list and map it in as an Scala API method?

百般思念 提交于 2019-12-03 01:30:48
Wilfred Springer

How about using collect?

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

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

The better answer would have been, based on 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 comments to append a head to get a Scala 2.8 version of that is not very efficient, I'm afraid. Perhaps in that case I would stick to your own code. In any case, in order to make sure it returns an option, you should not call head, but headOption.

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

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

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

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

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.

This can do it, but it would be easier if you tell what you're really trying to achieve:

l.flatMap(n => if (n * 33 % 2 == 0) Some(n * 33) else None).headOption
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!