Asynchronous programming in Scala with Future

What is Future? A future object is an object whose value will be removed at some point in the future. This value is usually the result of a calculation process.

This calculation returns the result value, we say that the Future object has completed that value, and vice versa. If an Exception is returned, the Future object is said to have failed with the Exception. One characteristic of Future is that when a future is completed, whether it succeeds or fails, it can not be changed (becomes immutable).

+Creating a Future is as simple as that exmaple.

import scala.concurrent.Future

import scala.concurrent.ExecutionContext.Implicits.global

val f: Future[Int] = Future {

  16 * 8

}

++Future in Action

import scala.concurrent.duration.Duration

import scala.concurrent.{Await, Future}

import scala.concurrent.ExecutionContext.Implicits.global

def factorial(n: BigInt): BigInt = {

  if (n <= 1) 1

  else n * factorial(n – 1)

}

val futures = (0 to 9) map {

  i => Future {

    println(s“Input: $i”)

    val s = factorial(i)

    println(s“Result for $i: $s”)

    s.toString()

  }

}

val f = Future.reduce(futures) { (s1, s2) => s1 + ‘,’ + s2 }

val n = Await.result(f, Duration.Inf)

println(n)

Result:

Input: 1

Input: 0

Result for 0: 1

Result for 1: 1

Input: 2

Result for 2: 2

Input: 4

Input: 3

Result for 3: 6

Input: 5

Result for 4: 24

Result for 5: 120

Input: 6

Result for 6: 720

Input: 8

Result for 8: 40320

Input: 9

Result for 9: 362880

Input: 7

Result for 7: 5040

1,1,2,6,24,120,720,5040,40320,362880

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s