地图操作理解结果的 Scala 以 Int 形式出现

Scala for comprehension result of map operation is coming as Int

请看下面的代码,

`

val d= for{
      t <- db.getSomething()
      ids <- t.map(_.id).toSeq
      histo <- fetchOtherRelatedDetails(ids)
    } yield histo

`

在这里,db.getSomething 返回一个 Future[Seq[SomeObject]],所以我试图获取对象,然后将它们的 ID 映射到列表中,然后想调用另一个函数来处理用于在 Future 中获取结果的 ID。 TYhe 编译器的问题是它将 ids 作为 Int 应该是 Seq[Int]

我是不是做错了什么?

乍一看,你的 for-comprehension 类型不匹配:

for {
  t <- db.getSomething()
  ids <- t.map(_.id).toSeq
  histo <- fetchOtherRelatedDetails(ids)
} yield histo

这个脱糖到

db.getSomething().flatMap { t =>
  t.map(_.id).toSeq.flatMap { ids =>
//^_______________________^ 
// the return type of this expression is Seq[A], but Future[A] is expected
    fetchOtherRelatedDetails(ids).map(histo => histo)
  }
}

如内联所述,您不能在需要 Future 的地方 return Seq。换句话说,<- 右边的所有表达式必须有一个共同的 "container"(在这种情况下为 Future),以便理解类型检查。

在这种特定情况下,您可以使用赋值而不是 flatMap (<-)

来修复它
for {
  t <- db.getSomething()
  ids = t.map(_.id).toSeq
  histo <- fetchOtherRelatedDetails(ids)
} yield histo