使用for / yield从序列中删除元素

时间:2015-07-20 14:35:51

标签: scala

给定Future[Seq[Widget]],其中Widget包含amount : Int属性,我想返回Seq[Widget],但只返回其金额值为Widget的{​​{1}}大概超过100.我相信for { if … } yield { }结构会给我我想要的但不确定如何过滤序列。我有:

val myWidgetFuture :  Future[Seq[Widget]] = ...

for {
  widgetSeq <- myWidgetFuture
  if (??? amount > 100) <— what to put here?
}  yield {
  widgetSeq
}

如果有一种干净的非收益方式,这对我也有用。

2 个答案:

答案 0 :(得分:6)

你甚至不需要yield。使用map

val myWidgetFuture: Future[Seq[Widget]] = ???

myWidgetFuture map { ws => ws filter (_.amount > 100) }

答案 1 :(得分:2)

如果您想将for … yieldif过滤器一起使用,则需要使用两个for

for {
  widgetSeq <- myWidgetFuture
} yield for {
  widget <- widgetSeq
  if widget.amount > 100
} yield widget