如何在列表中找到匹配的元素并将其映射为 Scala API 方法? [英] How to find a matching element in a list and map it in as an Scala API method?
问题描述
是否有一种方法可以在不执行这两种方法的情况下执行以下操作:find
和 map
?
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) // returns Some(66)
推荐答案
使用 collect 怎么样?
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.
更好的答案是,基于 Scala 2.9:
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 }
在评论中建议附加一个 head
以获得 Scala 2.8 版本的解决方案不是很有效,恐怕.也许在那种情况下,我会坚持使用您自己的代码.无论如何,为了确保它返回一个选项,你不应该调用head
,而是headOption
.
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
这篇关于如何在列表中找到匹配的元素并将其映射为 Scala API 方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!