Skip to content

Instantly share code, notes, and snippets.

View rdecaire's full-sized avatar

Robert DeCaire rdecaire

  • Inflection Group
  • Toronto
View GitHub Profile
future.onComplete{
case Success(result) => println(result)
case Failure(t) => println("failed with " + t.getMessage)
}
Future.failed(new Exception).recover{
case e: Exception => "I'm a default value!"
}
// once completed, this is:
// scala.concurrent.Future[String] = Future(Success(I'm a default value))
Future.successful("I succeed synchronously")
// scala.concurrent.Future[String] = Future(Success(I succeed synchronously))
Future.failed(new Exception("I fail synchronously"))
// scala.concurrent.Future[Nothing] = Future(Failure(java.lang.Exception: I fail synchronously))
def future1 = Future{Thread.sleep(randomMillis); "hello"}
def future2 = Future{Thread.sleep(randomMillis); " "}
def future3 = Future{Thread.sleep(randomMillis); "world"}
for {
s1 <- future1
s2 <- future2
s3 <- future3
} yield s1 + s2 + s3
val future1 = Future{Thread.sleep(randomMillis); "hello"}
val future2 = Future{Thread.sleep(randomMillis); " "}
val future3 = Future{Thread.sleep(randomMillis); "world"}
for {
s1 <- future1
s2 <- future2
s3 <- future3
} yield s1 + s2 + s3
import scala.util.Random
def randomMillis = Random.nextInt(5000).toLong
val future1 = Future{Thread.sleep(randomMillis); "hello"}
val future2 = Future{Thread.sleep(randomMillis); " "}
val future3 = Future{Thread.sleep(randomMillis); "world"}
future1.flatMap(s1 => future2.flatMap(s2 => future3.map(s3 => s1 + s2 + s3)))
Future("hello").flatMap{
s1 => Future(" ").flatMap{
s2 => Future("world").map(s3 => s1 + s2 + s3)
}
}
// once completed this is:
// scala.concurrent.Future[String] = Future(Success(hello world))
val futureString = Future("hello").map(string => string + " world")
// Once completed, this is:
// scala.concurrent.Future[String] = Future(Success(hello world))
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
// Future is not imported by default
val future = Future{
Thread.sleep(50)
println("I completed")
}
val notFuture = {
println("I completed first!")
}
val tFail1: Try[String] = Try(throw new Exception("failed"))
val tFail2: Try[String] = Try(throw new Exception("failed again"))
val tFail3: Try[String] = Try(throw new Exception("failed one more time"))
tFail1.recoverWith{
case _ => tFail2
}.recoverWith{
case _ => tFail3
}.recover{
case _ => "I give up!"
}