为什么for-comp内部的for-comp不起作用 [英] Why does a for-comp inside of a for-comp not work
问题描述
以下可以正常工作:
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")
}
}
我收到类型不匹配错误:
I get a type mismatch error:
found : scala.concurrent.Future[play.api.mvc.Result]
[error] required: play.api.mvc.Result
[error] f1 <- ....
希望有人可以帮我解释一下.
Hoping someone can explain this for me.
推荐答案
添加类型注释可能有助于更清楚地了解正在发生的事情:
Adding type annotations might help make clearer what's going on:
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]]
类型.
By yielding a Future[Result]
(innerResult
), you're causing the outermost for
to be of type Future[Future[Result]]
.
我们知道result
必须是Future [???]类型(由第一个生成器的类型userService.getAll()
确定).它最终会成为Future[Future[Result]]
,因为您会产生Future[Result]
.
We know that result
is going to have to be of type Future[???] (determined by the type of the first generator, userService.getAll()
). It winds up being a Future[Future[Result]]
because you yield a Future[Result]
.
解决方案是生成Result
intead:
The solution is to yield a Result
intead:
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
这篇关于为什么for-comp内部的for-comp不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!