Skip to content

Instantly share code, notes, and snippets.

@mattroberts297
Created August 23, 2017 07:21
Show Gist options
  • Save mattroberts297/7969634d981b920a492617dbf7ed747d to your computer and use it in GitHub Desktop.
Save mattroberts297/7969634d981b920a492617dbf7ed747d to your computer and use it in GitHub Desktop.
Enriching the Future type in Scala
package com.example.syntax
import scala.concurrent.{ExecutionContext, Future}
object FutureExample {
import future._
def foobar(implicit ec: ExecutionContext): Future[String] = Future.recover {
for {
f <- Future.failed(new RuntimeException("Foo"))
} yield {
f
}
} {
case _: RuntimeException => "Bar"
}
}
package com.example.syntax
import scala.concurrent.{ExecutionContext, Future}
package object future {
implicit class RichFutureType(f: Future.type) {
def recover[T, U >: T](
f: Future[T]
)(
pf: PartialFunction[Throwable, U]
)(
implicit
ec: ExecutionContext
): Future[U] = {
f.recover(pf)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment