功能性尝试&赶上斯卡拉 [英] functional try & catch w/ Scala

查看:101
本文介绍了功能性尝试&赶上斯卡拉的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Scala中打开一个资源并应用其方法比使用 vals 这个方法(直接从java中直接转换)还有一种更具象征意义的方式,等等。

Is there a more idomatic way of opening a resource in Scala and applying methods to it than this method (tranlsated directly from java), using vals but also including the finally etc.

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()
}


推荐答案

在Github的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 object:

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 _ =>
}

这篇关于功能性尝试&赶上斯卡拉的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆