Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Either to Try and vice versa in Scala

Tags:

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.

like image 956
Michael Avatar asked Mar 20 '14 12:03

Michael


People also ask

What is either in Scala?

In Scala Either, functions exactly similar to an Option. The only dissimilarity is that with Either it is practicable to return a string which can explicate the instructions about the error that appeared.

What is try in Scala?

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. Instances of Try[T] , are either an instance of scala.


1 Answers

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) } 
like image 146
cmbaxter Avatar answered Sep 24 '22 21:09

cmbaxter