繁体   English   中英

为什么Scala的Try没有异常类型的类型参数?

[英]Why Scala's Try has no type parameter for exception type?

我很好奇为什么scala.util.Try没有像例如类型的类型参数

abstract class Try[+E <: Throwable, +T] {
  recoverWith[U >: T](f: PartialFunction[E, Try[E, U]]): Try[E, U]
  ...
}

有助于文档,例如

def parseInt(s: String): Try[NumberFormatException, Int]

仍然无法表达不相关的异常类型,如throws SecurityException, IllegalArgumentException ,但至少在这个方向上迈出了一步。

这可能是你正在寻找的:

import scala.util.control.Exception._
import scala.util.{ Success, Failure }

def foo(x: Int): Int = x match {
  case 0 => 3
  case 1 => throw new NumberFormatException
  case _ => throw new NullPointerException
}

val Success(3) = catching(classOf[NumberFormatException]).withTry(foo(0))
val Failure(_: NumberFormatException) = catching(classOf[NumberFormatException]).withTry(foo(1))
// val neverReturns = catching(classOf[NumberFormatException]).withTry(foo(2))

请参阅scala.util.control.Exception $


然而,没有办法将Try[T]专门Try[ExcType, T]假设的Try[ExcType, T] ; 为了使这种工作,你会需要这样的东西Either (但可能是一些更复杂的如scalaz.\\/或,超过1异常类,无形的Coproduct ):

def bar(x: Int): Either[NumberFormatException, Int] = {
  catching(classOf[NumberFormatException]).withTry(foo(x)) match {
    case Success(x) => Right(x)
    case Failure(exc) => Left(exc.asInstanceOf[NumberFormatException])
  }
}

println(bar(0)) // Right(3)
println(bar(1)) // Left(java.lang.NumberFormatException)
// println(bar(2)) // throws NullPointerException

应该可以将其概括为适用于任意数量的异常类型的通用帮助程序。 你肯定会与无形工作Coproduct设施,在抽象元数在这种情况下。 不幸的是,这是一项非常重要的练习,我现在没有时间为你实现这一点。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM