以下操作正常:
def show(id: Int) = myAction asyc {
for {
users <- userService.getAll()
locations <- locationService.getByUsers(users)
} yield {
Ok("hi")
}
}
但如果我这样做:
for {
users <- userService.getAll()
locations <- locationService.getByUsers(users)
} yield {
for {
f1 <- ...
f2 <- ....
} yield {
Ok("hi")
}
}
我得到一个类型不匹配错误:
found : scala.concurrent.Future[play.api.mvc.Result]
[error] required: play.api.mvc.Result
[error] f1 <- ....
希望有人能为我解释一下。
添加类型注释可能有助于更清楚地了解发生了什么:
val result: Future[Future[Result]] = for {
users <- userService.getAll()
locations <- locationService.getByUsers(users)
} yield {
val innerResult: Future[Result] = for {
f1 <- ...
f2 <- ....
} yield {
Ok("hi")
}
innerResult
}
通过生成Future[Result]
(innerResult
),可以使最外层的for
为Future[Future[Result]]
类型。
我们知道result
必须是Future[???]类型(由第一个生成器userService.getAll()
的类型决定)。它最终成为Future[Future[Result]]
,因为你产生了Future[Result]
。
解决方案是生成Result
整数:
def foo(users: Seq[User], locations: Seq[Location]): Future[Result] = {
for {
f1 <- ...
f2 <- ....
} yield {
Ok("hi")
}
}
for {
users <- userService.getAll()
locations <- locationService.getByUsers(users)
result <- foo(users, locations)
} yield result