Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elegant Handling of Scala Future[Either]]

Tags:

scala

either

I have a type whose shape is like this:

val myType: Future[Either[MyError, TypeA]] = // some value

I know that I could pattern match on this and get to the Right or Left type, but the problem is that I would have to nest my pattern matching logic. I'm looking for much more elegant way of handling this? Any suggestions?

like image 997
joesan Avatar asked Nov 28 '25 15:11

joesan


1 Answers

If you encode your MyError as an exception, you don't need the Either anymore and can simply patternMatch against the completion, or use a recoverWith to map it to another type:

myType.onComplete {
  case Success(t) =>
  case Failure(e) =>
}

To map your existing Either types you could do something like this:

case class MyException(e: MyError) extends Exception

def eitherToException[A](f: Future[Either[MyError,A]]): Future[A] = {
  f.flatMap {
    case Left(e) => Future.failed(MyException(e))
    case Right(x) => Future.successful(x)
  }
}

val myType2 = eitherToException(myType)

Alternatively, if MyError and TypeA are under your control, you could create a common super type and pattern match against that:

sealed trait MyResult
final case class MyError() extends MyResult
final case class TypeA() extends MyResult

myType.map {
  case MyError() => ...
  case TypeA() => ...
}
like image 198
Arne Claassen Avatar answered Nov 30 '25 06:11

Arne Claassen