我一直在搞清楚为什么这不起作用:
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))
}
}
我希望这打印&#34; abc&#34;,但没有真正发生。
答案 0 :(得分:7)
您正在执行一个独立程序,问题是主线程在未来完成之前终止,看看您可以使用的东西:
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)
}
}