在 Scala 中使用循环时使事情不可变

Sar*_*ain 1 functional-programming scala immutability purely-functional scala-collections

我在 Scala 中编写了几行代码,但不知道如何使用不可变变量 (val) 使同样的事情工作。任何帮助都感激不尽。

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)
  }
}
Run Code Online (Sandbox Code Playgroud)

任何人都可以帮助我将所有 var 转换为 val 并使其更具功能性吗?提前致谢!:)

Mat*_*zok 7

使用.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
  }
Run Code Online (Sandbox Code Playgroud)

  • @SarfarazHussain 考虑接受答案[接受答案如何运作?](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) (2认同)