flatMap可能是你在寻找什么,但地图功能记录的副作用,如果马上点是一个视图可能不会出现这些副作用:
val convertedPoints = points.view.flatMap { p =>
try {
Some(p.convert)
} catch {
case e : Exception =>
// Log error
None
}
}
println("Conversion complete")
println(convertedPoints.size + " were converted correctly")
这将打印:
Conversion complete
[Error messages]
x were converted correctly
在你的情况下,放弃视图,你可能没事。 :)
要使转换为纯函数(无副作用),您可能会使用Either。虽然我不认为这是值得的,这里(除非你真正想要做的错误的东西),这是一个使用它的一个相当完整的例子:
case class Point(x: Double, y: Double) {
def convert = {
if (x == 1.0) throw new ConversionException(this, "x is 1.0. BAD!")
else ConvertedPoint(x, y)
}
}
case class ConvertedPoint(x: Double, y: Double)
class ConversionException(p: Point, msg: String) extends Exception(msg: String)
val points = List(Point(0,0), Point(1, 0), Point(2,0))
val results = points.map { p =>
try {
Left(p.convert)
} catch {
case e : ConversionException => Right(e)
}
}
val (convertedPoints, errors) = results.partition { _.isLeft }
println("Converted points: " + convertedPoints.map(_.left.get).mkString(","))
println("Failed points: " + errors.map(_.right.get).mkString(","))
你偷了我的答案,但+1更好地解释它:-)欢迎来到SO。 – 2010-11-03 22:04:53
同意 - 你的答案是100%正确(和一个灵感),但我认为增加更多的细节证明另一个答案,而不仅仅是一个评论。 :) – DaGGeRRz 2010-11-07 01:28:29