功能尝试 &使用 Scala [英] Functional try & catch with Scala
本文介绍了功能尝试 &使用 Scala的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有比这个方法(直接从java翻译)在Scala中打开资源并对其应用方法更惯用的方法:
Is there a more idiomatic way of opening a resource in Scala and applying methods to it than this method (translated directly from java):
var is: FileInputStream = null
try {
is = new FileInputStream(in)
func(is)
} catch {
case e: IOException =>
println("Error: could not open file.")
println(" -> " + e)
exit(1)
} finally {
if(is) is.close()
}
推荐答案
贷款模式在 Josh Suereth 的 scala-arm 库.
The loan pattern is implemented in various ways in Josh Suereth's scala-arm library on github.
然后您可以使用这样的资源:
You can then use a resource like this:
val result = managed(new FileInputStream(in)).map(func(_)).opt
这将返回包裹在 Option
中的 func
的结果,并负责关闭输入流.
which would return the result of func
wrapped in an Option
and take care of closing the input stream.
为了处理创建资源时可能出现的异常,可以结合scala.util.control.Exception
对象:
To deal with the possible exceptions when creating the resource, you can combine with the scala.util.control.Exception
object:
import resource._
import util.control.Exception.allCatch
allCatch either {
managed(new FileInputStream(in)).map(func(_)).opt
} match {
case Left(exception) => println(exception)
case Right(Some(result)) => println(result)
case _ =>
}
这篇关于功能尝试 &使用 Scala的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文