在 Scala 中尝试,反之亦然 [英] Either to Try and vice versa in Scala
问题描述
在 Scala 标准库中是否有任何从 Either
到 Try
的转换,反之亦然?也许我遗漏了一些东西,但我没有找到.
Are there any conversions from Either
to Try
and vice versa in the Scala standard library ? Maybe I am missing something but I did not find them.
推荐答案
据我所知,这在标准库中是不存在的.尽管 Either
通常与 Left
失败而Right
成功一起使用,但它确实旨在支持两个概念可能的返回类型,其中一个不一定是失败案例.我猜这些人们期望存在的转换并不存在,因为 Either
并没有像 Try
那样真正设计为成功/失败 monad.话虽如此,自己丰富 Either
并添加这些转换将非常容易.这可能看起来像这样:
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. 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. Having said that it would be pretty easy to enrich Either
yourself and add these conversions. 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)
}
这篇关于在 Scala 中尝试,反之亦然的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!