Created
August 23, 2017 07:21
-
-
Save mattroberts297/7969634d981b920a492617dbf7ed747d to your computer and use it in GitHub Desktop.
Enriching the Future type in Scala
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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" | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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