简体   繁体   English

在Scala中要么尝试,要么相反

[英]Either to Try and vice versa in Scala

Are there any conversions from Either to Try and vice versa in the Scala standard library ? 在Scala标准库中是否有来自Either to Try和反之亦然的转换? Maybe I am missing something but I did not find them. 也许我错过了一些东西,但我找不到它们。

To the best of my knowledge this does not exist in the standard library. 据我所知,标准库中不存在这种情况。 Although an Either is typically used with the Left being a failure and the Right being a success, it was really designed to support the concept of two possible return types with one not necessarily being a failure case. 虽然Either通常用于Left是失败而Right是成功的,但它实际上是为了支持两种可能的返回类型的概念,其中一种不一定是失败的情况。 I'm guessing these conversions that one would expect to exist do not exist because Either was not really designed to be a Success/Fail monad like Try is. 我猜这些人们期望存在的转换是不存在的,因为Either并不是真的被设计为像Try那样的成功/失败单子。 Having said that it would be pretty easy to enrich Either yourself and add these conversions. 话虽如此,将是很容易充实Either自己并添加这些转换。 That could look something like this: 这可能看起来像这样:

object MyExtensions {
  implicit class RichEither[L <: Throwable,R](e:Either[L,R]){
    def toTry:Try[R] = e.fold(Failure(_), Success(_))
  }

  implicit class RichTry[T](t:Try[T]){
    def toEither:Either[Throwable,T] = t.transform(s => Success(Right(s)), f => Success(Left(f))).get
  }  
}

object ExtensionsExample extends App{
  import MyExtensions._

  val t:Try[String] = Success("foo")
  println(t.toEither)
  val t2:Try[String] = Failure(new RuntimeException("bar"))
  println(t2.toEither)

  val e:Either[Throwable,String] = Right("foo")
  println(e.toTry)
  val e2:Either[Throwable,String] = Left(new RuntimeException("bar"))
  println(e2.toTry)
}
import scala.util.{ Either, Failure, Left, Right, Success, Try }

implicit def eitherToTry[A <: Exception, B](either: Either[A, B]): Try[B] = {
  either match {
    case Right(obj) => Success(obj)
    case Left(err) => Failure(err)

  }
}
implicit def tryToEither[A](obj: Try[A]): Either[Throwable, A] = {
  obj match {
    case Success(something) => Right(something)
    case Failure(err) => Left(err)
  }
}

在Scala 2.12.x中尝试使用toEither方法: http ://www.scala-lang.org/api/2.12.x/​​scala/util/Try.html#toEither:scala.util.Either[Throwable,T ]

The answer depends on how to convert the Failure to Left (and vice versa). 答案取决于如何将Failure转换为Left (反之亦然)。 If you don't need to use the details of the exception, then Try can be converted to Either by going the intermediate route of an Option : 如果您不需要使用异常的详细信息,则可以通过转到Option的中间路由将Try转换为Either

val tried = Try(1 / 0)
val either = tried.toOption.toRight("arithmetic error")

The conversion the other way requires you to construct some Throwable. 另一种方式的转换需要你构造一些Throwable。 It could be done like this: 可以这样做:

either.fold(left => Failure(new Exception(left)), right => Success(right))

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

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