Tutorial by Examples

import scala.concurrent.Future import scala.concurrent.ExecutionContext.Implicits.global object FutureDivider { def divide(a: Int, b: Int): Future[Int] = Future { // Note that this is integer division. a / b } } Quite simply, the divide method creates a Future tha...
The easiest way to consume a successful Future-- or rather, get the value inside the Future-- is to use the map method. Suppose some code calls the divide method of the FutureDivider object from the "Creating a Future" example. What would the code need to look like to get the quotient of...
Sometimes the computation in a Future can create an exception, which will cause the Future to fail. In the "Creating a Future" example, what if the calling code passed 55 and 0 to the divide method? It'd throw an ArithmeticException after trying to divide by zero, of course. How would t...
The previous examples demonstrated the individual features of a Future, handling success and failure cases. Usually, however, both features are handled much more tersely. Here's the example, written in a neater and more realistic way: object Calculator { def calculateAndReport(a: Int, b: Int...
In some cases it is necessary to calculate a variable amount of values on separate Futures. Assume to have a List[Future[Int]], but instead a List[Int] needs to be processed. Then the question is how to turn this instance of List[Future[Int]] into a Future[List[Int]]. For this purpose there is the s...
The for comprehension is a compact way to run a block of code that depends on the successful result of multiple futures. With f1, f2, f3 three Future[String]'s that will contain the strings one, two, three respectively, val fCombined = for { s1 <- f1 s2 <- f2 ...

Page 1 of 1