给定一个列表 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), ...)
...我需要创建一个序列
Future
s 用于所有具有类型的订单(即定义了 orderType
):val transactions: Seq[Future[Transaction]] = orders.filter(
_.orderType.isDefined).map { case order =>
trxService.findTransactions(order.id) // this returns a Future[Transaction]
}
)
上面的代码首先调用
filter
,这会创建一个新的 List
仅包含带有 orderType
的订单设置为 Some
,然后创建一个序列 Future
不在了。有没有更有效的方法来实现这一目标?
最佳答案
您可以聚合filter
和 map
使用 collect
val transactions: Seq[Future[Transaction]] = orders.collect {
case order if order.orderType.isDefined => trxService.findTransactions(order.id)
}
关于Scala:更有效的过滤列表和创建 future 序列的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32081664/