Scala: A More Effective Way to Filter a List and Create a Future Sequence

Given the list of objects Order...

case class Order(val id: String, val orderType: Option[String])
case class Transaction (val id: String, ...)

val orders = List(Order(1, Some("sell")), Order(2, None), ...)

... I need to create a sequence Futurefor all those orders that are of type (i.e. orderType):

val transactions: Seq[Future[Transaction]] = orders.filter(
  _.orderType.isDefined).map { case order =>
    trxService.findTransactions(order.id) // this returns a Future[Transaction]
  }
)

In the above code, it is first called filter, which creates a new Listone containing only orders with orderTypeinstalled on Some, and then creates a sequence from it Future. Is there a more efficient way to do this?

+4
source share
1 answer

You can aggregate filterand mapwith the help ofcollect

val transactions: Seq[Future[Transaction]] = orders.collect {
  case order if order.orderType.isDefined => trxService.findTransactions(order.id)
}
+8
source

All Articles