Search code examples
scalafunctional-programmingimmutabilityscala-collectionspurely-functional

Making things immutable while working with loops in Scala


I have written a few lines of code in Scala, but don't know how to make the same thing work with immutable variables (val). Any help will be much appreciated.

class Test {

  def process(input: Iterable[(Double, Int)]): (Double, Int) = {
    var maxPrice: Double = 0.0
    var maxVolume: Int = 0

    for ((price, volume) <- input) {
      if (price > maxPrice) {
        maxPrice = price
      }
      if (volume > maxVolume) {
        maxVolume = volume
      }
    }

    (maxPrice, maxVolume)
  }
}

Can anyone help me in converting all the var to val and making it more functional? Thanks in advance! :)


Solution

  • Use .foldLeft:

    def process(input: Iterable[(Double, Int)]): (Double, Int) =
      input.foldLeft(0.0 -> 0) { case ((maxPrice, maxVolume), (price, volume)) =>
        val newPrice = if (maxPrice < price) price else maxPrice
        val newVolume = if (maxVolume < volume) volume else maxVolume
        newPrice -> newVolume
      }