Reputation: 1081
In the following code I have a Play for Scala function with a future
inside a yield
. I get a compilation error type mismatch; found : scala.concurrent.Future[Nothing] required: play.api.mvc.Result
. Shouldn't I flatMap the future inside the yield to return the Ok
response?
def f1 = Future { 1 }
def f2 = Future { 2 }
def index = Action.async (parse.json) { request =>
for { x1 <- f1 }
yield {
val f = f2
f.flatMap { result =>
Ok("X")
}
}
}
Upvotes: 1
Views: 657
Reputation: 2733
No, when you say flatMap
you are saying that the result returned in the function is a Future[T]
, which in your example it returns a Result
, so just using a map
would work, but is not super idiomatic as you have to flatten
as you wind up with a Future[Future[Result]]
:
(for { x1 <- f1 } yield {
val f = f2
f.map( result =>
Ok("X")
)
}).flatten
What is more idiomatic is to use a for comprehension for the whole thing:
for {
x1 <- f1
x2 <- f2
} yield {
Ok("X")
}
Upvotes: 4