0

Is there a construct which allows to drop the repetition of the 0.0 routine below

val price: Option[Double] = ???

price match {
  case Some(d) =>  
    if (isPriceFair(d))  
      d  
    else  
      0.0  
  case _ =>  
    0.0  
}
2
  • 1
    You can move the if to the case, you could also use filter + getOrElse. Commented Jun 24 at 17:14
  • have just edited the question - it does not allow to move the if into the case Commented Jun 24 at 17:16

1 Answer 1

4

Try matching with a pattern guard:

price match {
  case Some(d) if d > 0 => d 
  case _                => 0.0  
}
price match {
  case Some(d) if isPriceFair(d) => d 
  case _                         => 0.0  
}

Please see https://docs.scala-lang.org/tour/pattern-matching.html#pattern-guards

Or

price.filter(_ > 0).getOrElse(0.0)
price.filter(isPriceFair).getOrElse(0.0)

https://scastie.scala-lang.org/DmytroMitin/C5LtgVbuSg6BsQKp2BqFqQ/1

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.