Removing elements from a sequence using for / yield

Given Future[Seq[Widget]]

where the Widget contains the property amount : Int

, I would like to return Seq[Widget]

, but only for those Widget

with a value greater than 100. I believe the construct for { if … } yield { }

will give me what I want, but I'm not sure how to filter through the Sequence. I have:

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

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

      

If you have a clean no-harvest way that will also work for me.

+3


source to share


2 answers


You don't even need to yield

. Use map

.



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

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

      

+6


source


If you want to use for … yield

with a filter if

, you need to use two for

s:



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

      

+2


source







All Articles