如果我有一个Seq,我可以解决map它。
val ss = Seq("1", "2", "3")
println(ss.map(s => s.toInt)) // List(1, 2, 3)
Run Code Online (Sandbox Code Playgroud)
但是有时,传递给您的功能map可能会失败。
val ss = Seq("1", "2", "c")
println(ss.map(s => try { Success(s.toInt) } catch { case e: Throwable => Failure(e) })) // List(Success(1), Success(2), Failure(java.lang.NumberFormatException: For input string: "c"))
Run Code Online (Sandbox Code Playgroud)
最后一个将返回Seq[Try[Int]]。我真正想要的是一个Try[Seq[Int]],如果映射中的任何一个是Failure,它将停止迭代并返回Failure。如果没有错误,我希望它只返回从拆包的所有转换后的元素Try。
Scala的惯用方式是什么?
您可能想得太多。您中的匿名函数与map基本上相同Try.apply。如果你想结束了Try[Seq[Int]],那么你可以包装Seq在Try.apply与map内:
scala> val ss = Try(Seq("1", "2", "c").map(_.toInt))
ss: scala.util.Try[Seq[Int]] = Failure(java.lang.NumberFormatException: For input string: "c")
Run Code Online (Sandbox Code Playgroud)
如果任何toInts失败,它将抛出异常并停止执行,并成为一个Failure。
| 归档时间: |
|
| 查看次数: |
905 次 |
| 最近记录: |