0

I have a sequence of ids and a function which return an Option[workItem] for each id. All I want to do is generate a sequence of workItem from these two things. I tried various combinations of maps, foreach and for comprehension and nothing works.

def getWorkItems(ids: Future[Seq[Id]]): Future[Seq[Option[WorkItem]]] = {
   ids.map {
        id: workItemId => id.map(getWorkItem(_)
  }
}

This gives me error - Expression of type Seq[Option[WorkItem] doesn't conform to expected type _B

I tried foreach -

def getWorkItems(ids: Future[Seq[Id]]): Future[Seq[Option[WorkItem]]] = {
   ids.map {_.foreach(getWorkItem(_)}      
}

This gives me error - Expression of type Unit does not conform to expected type _B

I am not sure what this _B type is and how do I go about this transformation.

ocwirk
  • 1,079
  • 1
  • 15
  • 35

1 Answers1

1

Will work almostly as you expected.

trait o {

  class Id  {}
  class WorkItem { }

  def getWorkItem(id: Id): Option[WorkItem]

  def getWorkItems(ids: Future[Seq[Id]]): Future[Seq[Option[WorkItem]]] = {
    val res = ids.map { idsSeq =>
      idsSeq.map { id =>
        getWorkItem(id)
      }
    }
    res
  }



}

But as for me getWorkItems should return Future[Seq[WorkItem]] than instead of internal map you can use flatMap

  def getWorkItems(ids: Future[Seq[Id]]): Future[Seq[WorkItem]] = {
    val res = ids.map { idsSeq =>
      idsSeq.flatMap { id =>
        getWorkItem(id)
      }
    }
    res
  }
vvg
  • 6,325
  • 19
  • 36