Skip to content

Instantly share code, notes, and snippets.

@atamborrino
Last active January 31, 2017 09:20
Show Gist options
  • Save atamborrino/d3660ae7910ae8ec8dd67ec023386478 to your computer and use it in GitHub Desktop.
Save atamborrino/d3660ae7910ae8ec8dd67ec023386478 to your computer and use it in GitHub Desktop.
UnfailableFuture is a subset type of Future that can not result in a failure.
import scala.concurrent.{ExecutionContext, Future}
import scala.util.control.NonFatal
// private constructor guarantees that we can not build a semantically incorrect UnfailableFuture
class UnfailableFuture[A] private (val value: Future[A]) extends AnyVal
object UnfailableFuture {
def apply[A](fut: Future[A], fallback: Throwable => A)(implicit ec: ExecutionContext): UnfailableFuture[A] = {
val futWithFallback = fut.recover {
case NonFatal(failure) => fallback(failure)
}
new UnfailableFuture(futWithFallback)
}
def successful[A](a: A) = new UnfailableFuture(Future.successful(a))
}
// Example: allow to safely wrap a processing function to pass it in failure-sensitive context (like .pipeTo in an actor)
// with type-checking.
def handleFailure(userProcessingFunction: Input => Future[Output]): Input => UnfailableFuture[Output] = {
...
}
class MyActor(userProcessingFunction: Input => UnfailableFuture[Output]) extends Actor {
...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment