scala - Try和Either有什么区别?

标签 scala

根据the documentation:

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中介绍了TryEitherOption之间的关系。有关TryEither之间关系的重点摘要如下:
Try[A]Either[Throwable, A]同构。换句话说,您可以将Try视为左边类型为EitherThrowable,并且可以将任何Either左边类型为ThrowableTry对待。通常将Left用于失败,将Right用于成功。

当然,不仅在值缺失或异常的情况下,还可以更广泛地使用Either。在其他情况下,Either可以帮助表达简单联合类型(其中value是两种类型之一)的语义。

在语义上,您可以使用Try来指示该操作可能会失败。在这种情况下,您可能会类似地使用Either,尤其是在您的“错误”类型不是Throwable的情况下(例如Either[ErrorType, SuccessType])。然后,当您对联合类型(例如Either)进行操作时,也可能会使用Either[PossibleType1, PossibleType2]

标准库不包括从EitherTry或从TryEither的转换,但是很容易根据需要丰富TryEither:

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/

相关文章:

xml - 构建 map [String,String]

mongodb - Scala 中是否存在用于 MongoDB "schema"升级的良好框架?

java - 在 .xml.scala 模板中将 Scala 字符串转换为 Xml

scala - 扩展 Scala Enumeration.Val 时如何获得正确的值类型

Scala 类型语法

scala - 此递归列表展平如何工作?

使用 "_"的 Scala 函数映射

scala - Scala 编程语言的目的是什么?

scala - 为什么与空 fs2.Stream 合并会改变程序的行为

scala - 在 Scala 中,我可以通过隐式转换引用私有(private)类型