The Try type represents a computation that may either result in an exception, or return a successfully computed value. It's similar to, but semantically different from the scala.util.Either type.
关于语义差异,文档未做进一步详细介绍。两者似乎都能交流成功和失败。你为什么要使用一个?
最佳答案
我在this answer中介绍了Try
,Either
和Option
之间的关系。有关Try
和Either
之间关系的重点摘要如下:Try[A]
与Either[Throwable, A]
同构。换句话说,您可以将Try
视为左边类型为Either
的Throwable
,并且可以将任何Either
左边类型为Throwable
的Try
对待。通常将Left
用于失败,将Right
用于成功。
当然,不仅在值缺失或异常的情况下,还可以更广泛地使用Either
。在其他情况下,Either
可以帮助表达简单联合类型(其中value是两种类型之一)的语义。
在语义上,您可以使用Try
来指示该操作可能会失败。在这种情况下,您可能会类似地使用Either
,尤其是在您的“错误”类型不是Throwable
的情况下(例如Either[ErrorType, SuccessType]
)。然后,当您对联合类型(例如Either
)进行操作时,也可能会使用Either[PossibleType1, PossibleType2]
。
标准库不包括从Either
到Try
或从Try
到Either
的转换,但是很容易根据需要丰富Try
和Either
:
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)
关于scala - Try和Either有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29779135/