Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: More Efficient Way to Filter a List and Create a Sequence of Futures

Tags:

scala

future

Given a list of Order objects...

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 of Futures for all those orders that have a type (i.e. orderType is defined):

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

The code above first invokes filter, which creates a new List containing only orders with orderType set to Some, and then creates a sequence of Futures out of it. Is there a more efficient way to accomplish this?

like image 281
j3d Avatar asked Feb 10 '23 06:02

j3d


1 Answers

You can aggregate filter and map using collect

val transactions: Seq[Future[Transaction]] = orders.collect {
  case order if order.orderType.isDefined => trxService.findTransactions(order.id)
}
like image 134
Gabriele Petronella Avatar answered Feb 24 '23 22:02

Gabriele Petronella