score:8
Accepted answer
def craziness[a](future: future[a])(default : => a)(error: throwable)(implicit ec: executioncontext): future[a] = {
val p = promise[a]()
import scala.util.{success, failure, try}
future.oncomplete {
case _: success[_] => p.failure(error)
case _: failure[_] => p.complete(try(default))
}
p.future
}
here's a repl session showing it work:
scala> val f1 = craziness[string](future("hello!"))("my crazy default")(new throwable("boom"))
f1: scala.concurrent.future[string] = scala.concurrent.impl.promise$defaultpromise@4d154ccd
scala> f1 oncomplete { println }
failure(java.lang.throwable: boom)
scala> val f2 = craziness[string](future(throw new exception("boom!")))("my crazy default")(new throwable("boom"))
f2: scala.concurrent.future[string] = scala.concurrent.impl.promise$defaultpromise@1890516e
scala> f2 oncomplete { println }
success(my crazy default)
edit:
for completeness, def craziness[a](future: future[a])
should probably be def craziness[a](future: => future[a])
score:0
in scala 2.12 you'll be able to use transform
and transformwith
to make this trivial.
but until then this should get you there:
implicit class invertfuture[t](val fut: future[t]) extends anyval {
def flip(recover: throwable => t)(fail: t => throwable)(implicit ec: executioncontext): future[t] =
fut.recover({ case t => recover(t) }).map(t => throw fail(t))
}
// and usage:
scala> future(1).flip(_ => 2)(_ => throw new illegalstateexception("ohnoes!")) oncomplete println
failure(java.lang.illegalstateexception: ohnoes!)
score:1
i think you are after recover
and recoverwith
constructs. here's a quick repl session to show its usage.
$ scala
welcome to scala version 2.10.4 (java hotspot(tm) 64-bit server vm, java 1.8.0_45).
type in expressions to have them evaluated.
type :help for more information.
scala> import scala.concurrent.future
import scala.concurrent.future
scala> import scala.concurrent.executioncontext.implicits.global
import scala.concurrent.executioncontext.implicits.global
scala> val failfuture = future(sys.error("boom"))
failfuture: scala.concurrent.future[nothing] = scala.concurrent.impl.promise$defaultpromise@6e06451e
scala> val defaultvalue = 100
defaultvalue: int = 100
scala> val futurerecoveredwithdefaultfuture = failfuture.recoverwith { case e: runtimeexception => future.successful(defaultvalue) }
futurerecoveredwithdefaultfuture: scala.concurrent.future[int] = scala.concurrent.impl.promise$defaultpromise@130161f7
scala> val futurerecoveredwithdefaultvalue = failfuture.recover { case e: runtimeexception => defaultvalue }
futurerecoveredwithdefaultvalue: scala.concurrent.future[int] = scala.concurrent.impl.promise$defaultpromise@3b69e7d1
checking if this really works:
scala> import scala.concurrent.duration._
import scala.concurrent.duration._
scala> import scala.concurrent.await
import scala.concurrent.await
scala> val res1 = await.result(futurerecoveredwithdefaultfuture, 1.second)
res1: int = 100
scala> val res2 = await.result(futurerecoveredwithdefaultvalue, 1.second)
res2: int = 100
Source: stackoverflow.com
Related Query
- Invert a Scala Future
- Elegant way to invert a map in Scala
- Future investment: Erlang vs. Scala
- Is Future in Scala a monad?
- Nashorn and Scala future to JS Promise conversion
- ListenableFuture to scala Future
- Convert a Java Future to a Scala Future
- Scala Future with filter in for comprehension
- Future with Timeout in Scala
- Get rid of Scala Future nesting
- Error handling Scala : Future For Comprehension
- What are the differences between a Scala Future and a Java Future
- What are advantages of a Twitter Future over a Scala Future?
- Convert scala future to java future
- Convert scala 2.10 future to scalaz.concurrent.Future // Task
- MongoDB scala driver: what is a best way to return Future when working with Observer callbacks?
- Converting Scala @suspendable Method into a Future
- Cancellation with Future and Promise in Scala
- Scala Future mapTo fails to compile because of missing ClassTag
- convert Scala Future to Twitter Future
- Scala for comprehension with future and options
- Kill or timeout a Future in Scala 2.10
- Scala future sequence and timeout handling
- Does a wait on Scala Future block thread?
- Scala Future for comprehension: sequential vs parallel
- replace a while loop with Future in scala
- JDBC calls wrapped in Scala Future
- Invert a Map (String -> List) in Scala
- scala future error for " Don't call `Awaitable` methods directly, use the `Await` object."
- Usage of Scala Future in Playframework?
More Query from same tag
- Varargs to tuple in scala
- cats' NonEmptyList vs scala stdlib ::
- Spark SQL filter multiple fields
- Why do we need the From type parameter in Scala's CanBuildFrom
- overloading methods based on implicits
- Create dataframe with header using header and data file
- weird async/multiple phenomenon in my Scala codes
- Search a folder with specific name in Scala
- Scala and Play! framework form error
- Interval merge using Spark Scala
- How to update elegantly the Failure exception of a Try?
- infer type parameter from function argument
- Can I define a nameless method in a Scala class?
- Performing a simple HTTP GET with Dispatch
- Scala Play Framework 2.1.1 JSON
- Running sbt test suite twice causes jdbc Driver not found error
- The "~:" is what meaning in slick and why the DateTime did not recognize
- Artifactory + Jenkins: Publishing to a maven repository from a freestyle build
- How can I extract results of aggregate queries in slick?
- SCALA - Curly brackets in subtype declarations
- Error while trying to import Array._ and import org.apache.spark.sql.functions._ in Spark Scala
- sbt is installed but not found
- Scala Futures and Promises Callback basics
- Scala function value as argument
- Flatten Scala Try
- What is the meaning of "val Class.Something(2,_) = doSomething()"?
- MVar tryPut returns true and isEmpty also returns true
- Scala type parameter with multiple types as result of function
- Split a list into sublist based on element types in scala
- How do I build a project that uses sbt as its build system?