Skip to content

Instantly share code, notes, and snippets.

@bhudgeons
Created July 15, 2013 21:29
Show Gist options
  • Save bhudgeons/6003673 to your computer and use it in GitHub Desktop.
Save bhudgeons/6003673 to your computer and use it in GitHub Desktop.
Populating an Abstract Trait's Requirements with Futures
import scala.concurrent._
import scala.util.{ Success, Failure }
import ExecutionContext.Implicits.global
import scala.concurrent.duration._
trait Calculator {
def hardToCalculate1: Int
def hardToCalculate2: Int
def hardToCalculate3: Int
def result1 = hardToCalculate1 + hardToCalculate2
def result2 = hardToCalculate2 + hardToCalculate3
def result3 = hardToCalculate1 + hardToCalculate3
}
object FutureTest extends App {
def f1 = future {
println("calculating 1")
1
}
def f2 = future {
println("calculating 2")
2
}
def f3 = future {
println("calculating 3")
3
}
// first try:
val myCalc = for {
m1 <- f1
m2 <- f2
m3 <- f3
} yield new Calculator {
def hardToCalculate1 = m1
def hardToCalculate2 = m2
def hardToCalculate3 = m3
}
myCalc onComplete {
case Success(calc) => println("Result: " + calc.result1)
}
// second try:
val calculator = new Calculator {
lazy val hardToCalculate1 = Await.result(f1, 10 seconds)
lazy val hardToCalculate2 = Await.result(f2, 10 seconds)
lazy val hardToCalculate3 = Await.result(f3, 10 seconds)
}
println("result: " + calculator.result1)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment