【发布时间】:2015-12-17 04:29:13
【问题描述】:
我在尝试编写返回 Future[Map[Int,Long]] 的方法时遇到问题。
我在一些迭代中得到了一个 Future[Future[..]]。所以我尝试了 flatMap 身份。
请参阅下面的代码和我现在收到的错误消息。我不确定现在发生了什么。
def aggregate(permissions: Vector[Permission]): Map[Int, Long]
def calculate(roleProfile: RoleProfile): Future[Map[Int, Long]] = {
val roleIds = roleProfile.roles.map(r => r.id)
db.run(permissionDao.getByRoles(roleIds.toList)).map {
permissions =>
aggregate(permissions)
}
}
def generate(roleGroupId: Int): Future[Map[Int, Long]] = {
for {
roleGroup <- roleGroupService.getById(roleGroupId)
roles <- roleGroupService.getRolesByGroupId(roleGroupId)
} yield {
calculate(RoleProfile(roleGroup.get.id, roles.toSet)) //flatMap identity
}
}
我收到有关方法“计算”的错误消息:
type mismatch;
[error] found : scala.concurrent.Future[Map[Int,Long]]
[error] required: Map[Int,Long]
[error] calculate(RoleProfile(roleGroup.get.id, roles.toSet)) //flatMap identity
现在如果删除 'flatMap identity' 的 cmets,我会收到此错误:
type mismatch;
[error] found : Map[Int,Long] => Map[Int,Long]
[error] required: Map[Int,Long] => scala.concurrent.Future[?]
[error] calculate(RoleProfile(roleGroup.get.id, roles.toSet)) flatMap identity
我很困惑,我怎样才能让它返回 Future[Map[Int, Long]]。
更重要的是,我似乎不明白这里发生了什么。如果您很感激,请分解。
【问题讨论】:
-
将对
calculate的调用放入 for 理解中,例如:c <- calculate(RoleProfile...然后yield c