Michael Michael - 1 year ago 85
Scala Question

Either to Try and visa versa in Scala

Are there any conversions from

and visa versa in the Scala standard library ? Maybe I am missing something but I did not find them.

Answer Source

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 pimp Either yourself and add these conversions. That could look something like this:

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

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

object PimpsExample extends App{
  import MyPimpings._

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

  val e:Either[Throwable,String] = Right("foo")
  val e2:Either[Throwable,String] = Left(new RuntimeException("bar"))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download