功能尝试和捕获与Scala

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)


Mar*_*ing 5

这可能是一个不希望功能化的情况.已经提到的贷款模式只是错误处理的比较版本的封装,但这与函数式编程无关,并且还负责处理错误.

如果你真的想要它的功能,你可以使用错误处理monad.出于好的理由,我提供的链接是Haskell特定的文档,因为Scala不支持这种"硬核"功能实践.

我会建议你采取必要的方式并最终使用try catch ...你也可以通过错误处理扩展贷款模式,但这意味着如果你想在某些情况下以不同方式处理错误,你必须编写特殊功能将不得不传递一个部分函数进行错误处理(这只是你已经在代码中的catch块中获得的内容).