scalafutureflatmapfor-comprehension

Deal with nested for-comprehension and futures in scala (value map is not a member of Any)


I saw many questions related to mine but none deal with my case.

I want to nest for-comprehension of future like in the code below:

def getVal(v: Int): Future[Double] = {
  Future(scala.math.sqrt(v >> 3))
}

val c = true
val t = for {

  x <- getVal(60)
  y <- getVal(52)
  o <-
    if (c) {
      for {
        a <- getVal(10)
        b <- getVal(5)
      } yield a > b
    } else true

} yield x >= y && o

but my code can't compile I got this error : value map is not a member of Any

I need help, please


Solution

  • Problem is here:

        if (c) {
          for {
            a <- getVal(10)
            b <- getVal(5)
          } yield a > b
        } else true
    

    Because it does (pseudocode):

       if (c) Future[Boolean]
       else Boolean
    

    The code common type is inferred to Any and then you end up with for-comprehension trying to call .map on Any value.

    Just wrap true with Future.successful(true).