功能性尝试赶上Scala [英] Functional try & catch with Scala

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

问题描述

在Scala中打开资源并将资源应用方法的方法比此方法(直接从Java直接翻译)是否有更惯用的方法:

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屋!

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