Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible in Scala to simplify the following if/else statement?

Tags:

scala

I'm trying to store the maximum price. There are some other business rules in there but the three nested if statements look very procedural and messy. I'm wondering if there is a nicer more functional way to express the following logic.

val sunsetTime1 = "14:00:00.000"
val maxPrices = new HashMap[String, Double]

if (trade.dateTime.before(time1)) {
  if (maxPrices.contains(sunsetTime1)) {
    if (maxPrices(sunsetTime1) < trade.price) {
      maxPrices.put(sunsetTime1, price)
    }
  }
  else {
    maxPrices.put(sunsetTime1, price)
  }

}
like image 923
deltanovember Avatar asked Aug 19 '11 02:08

deltanovember


1 Answers

I'm not an Scala expert, and you should check that code, but I guess pattern matching and Options are more Idiomatic Scala.

if (trade.dateTime.before(time1)) {
  maxPrices.get(sunsetTime1) match {
    case Some(oldPrice) if oldPrice < trade.price => maxPrices.put(sunsetTime1, price)
    case None => maxPrices.put(sunsetTime1, price)
  }
}

Cheers.

like image 155
Anthony Accioly Avatar answered Jan 03 '23 19:01

Anthony Accioly