-2

I'm having this issue where I use a for-comprehension in Scala to chain some Futures, and then get an instance of a class with some of those values. The problem is that the val I assign the value to, is of type Future[MyClass] instead of MyClass and I can't seem to figure out why.

The code is something like this:

val future = someService.someFutureReturningMethod()
val x = for{
    a <- future
    b <- someOtherService.someOtherFutureMethod(a)
} yield {
    MyClass(b.sth, b.sthElse)
}

The problem here is that x ends up being of type Future[MyClass] and not MyClass and I can't seem to figure out why.

Jaxidoxium
  • 33
  • 3
  • Possible duplicate of [Scala's "for comprehension" with futures](https://stackoverflow.com/questions/19045936/scalas-for-comprehension-with-futures) – Shankar Shastri Sep 18 '18 at 13:20

1 Answers1

4

That behavior is correct, you can use for comprehension because Future[T] understands flatMap and map methods.

The following code

val futureA = Future.successful(1)
val futureB = Future.successful(2)
val futureC = Future.successful(3)

val x1 = for {
  a <- futureA
  b <- futureB
  c <- futureC
} yield {
  a + b + c
}

It is compiled to

val x2 = futureA.flatMap {
  a => futureB.flatMap {
    b => futureC.map {
      c => a + b + c
    }
  }
} 

A call to Future.flatMap or Future.map is a Future. (it is the same with Option, Try, Either, etc)

If you want the result you need to wait for it.

Await.result(x, Duration(10, TimeUnit.SECONDS))
Sebastian Celestino
  • 1,388
  • 8
  • 15