问题描述
根据文档:
Try 类型表示可能导致异常,或返回一个成功计算的值.它类似于,但在语义上与 scala.util.Either 类型不同.
文档没有进一步详细说明语义差异是什么.两者似乎都能够传达成功和失败.为什么要使用一个?
The docs do not go into further detail as to what the semantic difference is. Both seem to be able to communicate successes and failures. Why would you use one over the other?
推荐答案
我在中介绍了 Try
、Either
和 Option
之间的关系这个答案.关于 Try
和 Either
之间关系的重点总结如下:
I covered the relationship between Try
, Either
, and Option
in this answer. The highlights from there regarding the relationship between Try
and Either
are summarized below:
Try[A]
与 Either[Throwable, A]
同构.换句话说,您可以将 Try
视为具有左类型 Throwable
的 Either
,并且您可以将任何 Either
code> 的左类型为 Throwable
作为 Try
.通常使用 Left
表示失败,使用 Right
表示成功.
Try[A]
is isomorphic to Either[Throwable, A]
. In other words you can treat a Try
as an Either
with a left type of Throwable
, and you can treat any Either
that has a left type of Throwable
as a Try
. It is conventional to use Left
for failures and Right
for successes.
当然,您也可以更广泛地使用 Either
,而不仅仅是在值缺失或异常的情况下.在其他情况下,Either
可以帮助表达简单联合类型(其中 value 是两种类型之一)的语义.
Of course, you can also use Either
more broadly, not only in situations with missing or exceptional values. There are other situations where Either
can help express the semantics of a simple union type (where value is one of two types).
在语义上,您可以使用 Try
来指示操作可能会失败.在这种情况下,您可能类似地使用 Either
,特别是如果您的错误"类型不是 Throwable
(例如 Either[ErrorType, SuccessType]
>).然后,当您对联合类型进行操作时,您也可以使用 Either
(例如 Either[PossibleType1,PossibleType2]
).
Semantically, you might use Try
to indicate that the operation might fail. You might similarly use Either
in such a situation, especially if your "error" type is something other than Throwable
(e.g. Either[ErrorType, SuccessType]
). And then you might also use Either
when you are operating over a union type (e.g. Either[PossibleType1, PossibleType2]
).
标准库不包括从 Either
到 Try
或从 Try
到 Either
的转换,但是根据需要丰富 Try
和 Either
非常简单:
The standard library does not include the conversions from Either
to Try
or from Try
to Either
, but it is pretty simple to enrich Try
, and Either
as needed:
object TryEitherConversions {
implicit class EitherToTry[L <: Throwable, R](val e: Either[L, R]) extends AnyVal {
def toTry: Try[R] = e.fold(Failure(_), Success(_))
}
implicit class TryToEither[T](val t: Try[T]) extends AnyVal {
def toEither: Either[Throwable, T] = t.map(Right(_)).recover(PartialFunction(Left(_))).get
}
}
这将允许您:
import TryEitherConversions._
//Try to Either
Try(1).toEither //Either[Throwable, Int] = Right(1)
Try("foo".toInt).toEither //Either[Throwable, Int] = Left(java.lang.NumberFormatException)
//Either to Try
Right[Throwable, Int](1).toTry //Success(1)
Left[Throwable, Int](new Exception).toTry //Failure(java.lang.Exception)
这篇关于Try 和Either 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!