scalapattern-matching

Transform a match to avoid duplicate


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  
}

Solution

  • 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