【问题标题】:Futures are causing me some confused, tried flatMap identity期货让我有些困惑,尝试过 flatMap 身份
【发布时间】: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]]。

更重要的是,我似乎不明白这里发生了什么。如果您很感激,请分解。

【问题讨论】:

标签: scala future


【解决方案1】:

由于calculate,就像你的getById等调用一样,返回一个Future,你应该可以简单地将它添加到理解的主要部分,例如:

def generate(roleGroupId: Int): Future[Map[Int, Long]] = {
  for {
    roleGroup <- roleGroupService.getById(roleGroupId)
    roles <- roleGroupService.getRolesByGroupId(roleGroupId)
    profile <- calculate(RoleProfile(roleGroup.get.id, roles.toSet))
  } yield { profile }
}

【讨论】:

  • @Blankman,添加到@Shadowlands 建议,您在calculate 之后直接写了flatMap,它只返回Future[Map[...]]。如果您将flatMap 用于整体理解,它会起作用。即:(for{...} yield{...}).flatMap(identity)
猜你喜欢
  • 1970-01-01
  • 2015-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-06
  • 2018-10-20
  • 2018-06-18
相关资源
最近更新 更多