A complete Future sample at Scala REPL

$ scala

Welcome to Scala 2.11.8 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_77).

Type in expressions for evaluation. Or try :help. scala>import concurrent.Future import concurrent.Future

scala>import concurrent.ExecutionContext.Implicits.global import concurrent.ExecutionContext.Implicits.global scala>import scala.util.{Success, Failure} import scala.util.{Success, Failure} scala>def createFuture():Future[Int] = {

| Future {

| val r = scala.util.Random

| if (r.nextInt(100)%2==0) 0 else throw new RuntimeException("ODD numbers are not good here :( ")

| }

| }

createFuture: ()scala.concurrent.Future[Int] scala>def evaluateFuture(f:Future[_]) {

| f.onComplete {

| case Success(i) => println(s"A Success $i ")

| case Failure(e) => println(s"Something went wrong. Ex: ${e.getMessage}")

| }

| }

evaluateFuture: (f: scala.concurrent.Future[_])Unit scala>evaluateFuture(createFuture)

scala>Something went wrong. Ex: ODD numbers are not good here :( evaluateFuture(createFuture)

A Success 0

scala>evaluateFuture(createFuture)

Something went wrong. Ex: ODD numbers are not good here :( scala>evaluateFuture(createFuture)

Something went wrong. Ex: ODD numbers are not good here :( scala>evaluateFuture(createFuture)

A Success 0

scala>evaluateFuture(createFuture)

A Success 0 scala>

There is a function called createFuture, which creates Future[lnt] each time you call it. In the preceding code, we use scala.util.Random to generate random numbers between 0 and 99. If the number is even, we return a 0, which means success. However, if the number is odd, we return a RuntimeException, which will mean a failure.

There is a second function called evaluateFuture, which receives any Future. We allow a result of any kind of generic parameterized type of function, because we used the magic underscore _. Then we apply Pattern Matcher with two case classes: Success and Failure. In both the cases, we just print on stdin. We also use another interesting and handy Scala feature called String interpolation. We need to we start the String with s before "". This allows us to use expressions with $ and ${} to evaluate any variable in the context. This is a different approach for String concatenation from what we have done so far. Later, we made 6 calls for the evaluteFuture function, passing a new Future each time, created by the function createFuture.

 
Source