lundi 27 novembre 2017

How to map sequence only if a condition applies with scala using an immutable approach?

Given a sequence of SomeFoo objects. If a condition applies I want to map it, otherwise return as is.

In a mutable way I probably would write it like this:

var prices: Seq[Price] = Seq(price1, price2, ...).map(doStuff).map(doSomeOtherStuff)
if (promo == "FOO") {
  prices = prices.map(price => {
     price.copy(amount = price.amount - someDiscount)
  })
}
prices

I was wondering if I could do something similar like this while keeping the immutable approach of scala. I want to apply a map function only if a condition applies. Yet instead of creating a temp var, I prefer to keep the chain.

Pseudocode:

val prices = Seq(price1, price2, ...)

prices
  .map(dosStuff)
  .map(doOtherStuff)
  .mapIf(promo == "FOO", calculatePromoPrice)

Aucun commentaire:

Enregistrer un commentaire