【发布时间】:2017-11-23 04:58:03
【问题描述】:
我之前在论坛中找到了我一直在寻找的问题的答案How to find a matching element in a list and map it in as an Scala API method?
// Returns Some(66)
List(1, 2, 3) collectFirst { case i if (i * 33 % 2 == 0) => i * 33 }
现在如果我用函数替换 if 子句
//
List(1, 2, 3) collectFirst { case i if ( test(i) > 0) => test(i) }
这可行,但 test() 将被评估两次。是否有更好的解决方案将函数应用于列表并在满足条件时返回结果(不必遍历所有元素并且不必两次调用函数(用于评估和返回值。
【问题讨论】: