Scala期货和Await.result()

时间:2017-10-02 22:42:03

标签: scala future

我希望以下代码会导致syncResult包含"字符串2",而是会收到错误java.lang.NoClassDefFoundError: Could not initialize class

import scala.concurrent.{Await, Future}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration._

def randomFunction1(): Future[String] = {
    Future.successful("string one")
}

def randomFunction2(): Future[String] = {
    Future.successful("string two")
}

val asyncResult: Future[String] = for {
    r1 <- randomFunction1()
    r2 <- randomFunction2()
} yield r2

val syncResult: String = Await.result(
    asyncResult,
    1.second
)

我得到了类似的结果。

import scala.concurrent.{Await, Future}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration._

def randomFunction1(): Future[String] = {
    Future.successful("string one")
}

def randomFunction2(): Future[String] = {
    Future.successful("string two")
}

val asyncResult: Future[String] = randomFunction1().flatMap(
    r1 => {
        randomFunction2()
    }
)

val syncResult: String = Await.result(
    asyncResult,
    1.second
)

我使用Scala 2.12.2解释程序使用:paste运行它。

我的代码出了什么问题?

1 个答案:

答案 0 :(得分:1)

这似乎与Scala REPL有关。