David
David

Reputation: 167

Scala futures and Await.result()

I expect the following code to result in syncResult containing "string two", but instead, I get the error 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
)

I get similar results with the following.

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
)

I'm using the Scala 2.12.2 interpreter to run this using :paste.

What's wrong with my code?

Upvotes: 2

Views: 3669

Answers (1)

David
David

Reputation: 167

This seemed to be an issue with the Scala REPL.

Upvotes: 1

Related Questions