如何在 Scala/ReactiveMongo 中映射两个“未来”结果?

How to map two `future` results in Scala/ReactiveMongo?

我有一个用 Play 和 ReactiveMongo 编写的应用程序,我想:

我有这个工作代码:

// Insert the landing page and wait for it to be inserted, so we can then get the new count of landing pages.
val futures = for {
  wr <- landingPagesCollection.insert(landingPage)
  count <- landingPagesCollection.count()
} yield count

futures.map { (count: Int) =>
  Created(Json.obj(
    "created" -> true,
    "landingPage" -> landingPage.toJson,
    "count" -> count
  ))
}

这段代码工作正常。但是,出于好奇,我想知道如何访问 wr (WriteResult) 价值。当我将代码更改为:

val futures = for {
  wr <- landingPagesCollection.insert(landingPage)
  count <- landingPagesCollection.count()
} yield (wr, count)

futures.map { (wr: WriteResult, count: Int) =>
  Created(Json.obj(
    "created" -> true,
    "message" -> s"You created landing page ${landingPage.name} (${landingPage.jobNumber}). The Git URI is '${landingPage.gitUri}'.",
    "landingPage" -> landingPage.toJson,
    "count" -> count,
    "writeResult" -> wr
  ))
}

我收到以下错误消息:

谁能解释一下如何在地图函数中访问 wr

尝试改变

futures.map { (wr: WriteResult, count: Int) =>

至:

futures.map { case (wr: WriteResult, count: Int) =>

或者只是:

futures.map { case (wr, count) =>

希望对您有所帮助

如果函数接受 2 个参数而不是元组,则您使用的语法有效

list.map((a: Int, b: String) => ...)

如果你需要一个元组,你可以这样做:

list.map(tuple: (Int, String) => {
   val (num, str) = tuple
   ...
})

或按照接受的答案中的建议传递部分功能。它将匹配参数(它匹配一个元组)并允许您稍后使用提取的值

list.map { case (a: Int, b: String) => ... }

请注意,在这种情况下需要花括号。

类型注释可以被删除,因为它们可以被编译器推断出来。