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 Future
s 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 Future
s out of it. Is there a more efficient way to accomplish this?
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With