OlivierBlanvillain
OlivierBlanvillain

Reputation: 7768

Abstraction for asynchronous computation that cannot fail

Scala Futures are a fine abstraction for asynchronous computation that can fail. What abstraction should I use when I know that there is no failure possible?

Here is a concrete use case:

case class Service123Error(e: Throwable)

val f1: Future[User] =
  service123.call()

val f2: Future[Either[Service123Error, User]] =
  f1.map(Right.apply)
    .recover { case e => Left(Service123Error(e)) }

In this code, the types do not model the fact that f2 always successfully completes. Given several values similar to f2, I know I can Future.sequence over them (i.e. without the fail fast behavior), but the types are not carrying this information.

Upvotes: 1

Views: 80

Answers (1)

0__
0__

Reputation: 67290

I would not stick an Either into a Future if it carries the error information. Simply use the failure side of the future.

Future(Right(User))           -> Future[User](User)
Future(Left(Service123Error)) -> Future[User](throw Service123Error)

Upvotes: 0

Related Questions