简体   繁体   English

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

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

I'm curious why scala.util.Try has no type parameter for the exception type like 我很好奇为什么scala.util.Try没有像例如类型的类型参数

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

Would help with documentation, eg 有助于文档,例如

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

Still won't be able to express disjoint exception types like throws SecurityException, IllegalArgumentException , but at least one step in this direction. 仍然无法表达不相关的异常类型,如throws SecurityException, IllegalArgumentException ,但至少在这个方向上迈出了一步。

This might be what you're looking for: 这可能是你正在寻找的:

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

See scala.util.control.Exception$ 请参阅scala.util.control.Exception $


However, there's no way to specialize Try[T] to something like the hypothetical Try[ExcType, T] ; 然而,没有办法将Try[T]专门Try[ExcType, T]假设的Try[ExcType, T] ; in order for that to work you'll need something like Either (but possibly something more sophisticated such as scalaz.\\/ , or, for more than 1 exception class, Shapeless' Coproduct ): 为了使这种工作,你会需要这样的东西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

It should be possible to generalize that into a generic helper that works with any number of exception types. 应该可以将其概括为适用于任意数量的异常类型的通用帮助程序。 You'd definitely have to work with Shapeless' Coproduct and facilities for abstracting over arity in that case. 你肯定会与无形工作Coproduct设施,在抽象元数在这种情况下。 Unfortunately, it's a non-trivial exercise and I don't have the time to implement that for you right now. 不幸的是,这是一项非常重要的练习,我现在没有时间为你实现这一点。

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

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