ocwirk
ocwirk

Reputation: 1089

Generate new scala sequence from another sequence

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.

Upvotes: 0

Views: 1145

Answers (1)

vvg
vvg

Reputation: 6385

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
  }

Upvotes: 1

Related Questions