Aar*_*ken 21 functional-programming scala
是否有更多的自动方式在Scala中打开资源并将方法应用于此方法(直接从java转换),使用__CODE__但也包括finally等.
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()
}
Run Code Online (Sandbox Code Playgroud)
huy*_*hjl 19
贷款模式在Josh Suereth的github上的scala-arm库中以各种方式实现.
然后,您可以使用这样的资源:
val result = managed(new FileInputStream(in)).map(func(_)).opt
Run Code Online (Sandbox Code Playgroud)
这将返回func包含在a中的结果Option并负责关闭输入流.
要在创建资源时处理可能的异常,您可以与scala.util.control.Exception对象结合使用:
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 _ =>
}
Run Code Online (Sandbox Code Playgroud)