为什么 scala.util.Failure 有一个类型参数? [英] Why does scala.util.Failure have a type parameter?
问题描述
scala.util.Failure
声明如下:
final case class Failure[+T](exception: Throwable) extends Try[T]`
它需要一个看起来完全没有必要的类型参数 T
,因为 Failure
可以很容易地被声明为 Try[Nothing] 的子类型代码>:
It takes a type parameter T
which looks completely unnecessary, given how Failure
could just as easily be declared as a sub-type of Try[Nothing]
:
final case class Failure(exception: Throwable) extends Try[Nothing]`
与 None
的声明方式相同:
in the same way that None
is declared like:
object None extends Option[Nothing]
确实,额外的类型参数成为了其他地方的痛点.这是Future.zip
:
Indeed, the extra type parameter becames a pain point elsewhere. Here is Future.zip
:
def zip[U](that: Future[U]): Future[(T, U)] = {
implicit val ec = internalExecutor
val p = Promise[(T, U)]()
onComplete {
case f: Failure[_] => p complete f.asInstanceOf[Failure[(T, U)]]
case Success(s) => that onComplete { c => p.complete(c map { s2 => (s, s2) }) }
}
p.future
}
行:
case f: Failure[_] => p complete f.asInstanceOf[Failure[(T, U)]]
可以简化为:
case f: Failure => p complete f
如果失败被声明为 Try[Nothing]
的子类型.
If failure had been declared a sub-type of Try[Nothing]
.
我觉得我一定在这里遗漏了一些东西.我可以为类型参数想出的唯一原因是声明一个表达式表示计算特定类型的失败,并明确表示它是一个失败,与仅使用 Try[T]
不同,但我无法想象真的需要这样做的情况.
I feel like I must be missing something here. The only reason I could come up with for the type parameter is to declare that an expression represents the failure to compute a particular type, and to make explicit it is a failure unlike just using Try[T]
, but I can't imagine a situation where this would really be needed.
推荐答案
Failure[+T]
中的 T
在尝试从故障中恢复时派上用场:recover[U >: T](rescueException: PartialFunction[Throwable, U]): Try[U]
The T
in Failure[+T]
comes in handy when trying to recover from the failure: recover[U >: T](rescueException: PartialFunction[Throwable, U]): Try[U]
这篇关于为什么 scala.util.Failure 有一个类型参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!