Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why this simple Scala for comprehension does not execute the futures?

I'm stuck figuring out why this does not work:

import scala.concurrent.future
import scala.concurrent.Future
import scala.concurrent.ExecutionContext

import scala.concurrent.ExecutionContext.Implicits.global

object FutureTest {

  def main(args: Array[String]) {
    val result1 = future("a")
    val result2 = future("b")
    val result3 = future("c")

    val res = for {
      r1 <- result1
      r2 <- result2
      r3 <- result3
    } yield (r1 + r2 + r3)

    for { r <- res} yield(println(r))
  }
}

I'm expecting this to print "abc", but nothing really happens.

like image 567
sscarduzio Avatar asked Jan 30 '26 15:01

sscarduzio


1 Answers

You are executing a stand alone program and the problem is that the main thread is terminated before the future can complete, to see something you could use this:

import scala.concurrent.future
import scala.concurrent.Future
import scala.concurrent.ExecutionContext

import scala.concurrent.ExecutionContext.Implicits.global

object FutureTest {

  def main(args: Array[String]) {
    val result1 = future("a")
    val result2 = future("b")
    val result3 = future("c")

    val res = for {
      r1 <- result1
      r2 <- result2
      r3 <- result3
    } yield (r1 + r2 + r3)

    val printing = for { r <- res} yield(println(r))

    Await.ready(printing, Duration.Inf)
  }
}
like image 112
Ende Neu Avatar answered Feb 02 '26 06:02

Ende Neu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!