首页 > 解决方案 > 在高阶函数scala中改变状态的函数方法

问题描述

考虑以下代码,

 1 var ip = ArrayBuffer[String]()
 2 ip += "1"
 3 println(ip)
 4 ip.clear()
 5 (1 to 10).foreach(ip += ("1"))
 6 println(ip)

ip在第 5 行中,在高阶函数中使用变量会导致异常。我知道使用var是不可取的,但我想知道如何在高阶函数中使用 vars。或者是否有管理状态的替代方法。

标签: scalascala-collections

解决方案


以下作品:

(1 to 10).foreach(_ => ip += "1")

foldLeft 功能更强大,您可以省去可变状态:

(1 to 10).foldLeft(List.empty[String]){
  case (acc, _) => "1" :: acc
}

输出:

List[String] = List(1, 1, 1, 1, 1, 1, 1, 1, 1, 1)

推荐阅读