加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

功能尝试和捕获w/Scala

发布时间:2020-12-16 09:38:02 所属栏目:安全 来源:网络整理
导读:在Scala中打开一个资源的方法比这种方法(直接从java转换)更方便地使用Scala并应用方法,使用val,而且还包括finally。 var is:FileInputStream = nulltry { is = new FileInputStream(in) func(is)} catch { case e:IOException = println("Error: could not
在Scala中打开一个资源的方法比这种方法(直接从java转换)更方便地使用Scala并应用方法,使用val,而且还包括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()
}

解决方法

Josh Suereth的 scala-arm图书馆在github上以多种方式实施贷款模式。

然后,您可以使用如下资源:

val result = managed(new FileInputStream(in)).map(func(_)).opt

这将返回包含在Option中的func的结果,并且关闭输入流。

要在创建资源时处理可能的异常,可以与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 _ =>
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读