Thursday, April 16, 2015

A little more on Scala Futures

After continuing the article and continuing to functional compositions and the flatmap.

I thought it helpful to include my Eclipse worksheet code, which can be played with and run.


import scala.concurrent._
import ExecutionContext.Implicits.global
import scala.util.{Try,Success,Failure}

object Actors3 {
  println("Actors3----")
  
  val r = scala.util.Random
  
  val usdQuote = future {
    Thread.sleep(1000)
    r.nextInt(10)
  }
  val canQuote = future {
    Thread.sleep(1000)
    r.nextInt(10)
  }

  val purchase = for {
    usd <- usdQuote
    can <- canQuote
    if (can > usd)
  } yield "Can Strong"
  
  purchase onSuccess {
    case e => println(s"e1=${e}")
  }

  println("This is the most interesting")
  val purchase2 = usdQuote flatMap {
    usd => canQuote.withFilter(can => (can > usd)).map(can => "Can Strong")
  } recover {
    case _ => "Falsies"
  }
  
  println(s"purchase2=${purchase2}")
  purchase2 onSuccess {
    case e => println(s"e2=${e}")
  }
  Thread.sleep(4000)
  println("End----")
}

No comments:

Post a Comment