高阶函数scala中状态变异的函数方法
考虑以下代码高阶函数scala中状态变异的函数方法,scala,scala-collections,Scala,Scala Collections,考虑以下代码 1 var ip = ArrayBuffer[String]() 2 ip += "1" 3 println(ip) 4 ip.clear() 5 (1 to 10).foreach(ip += ("1")) 6 println(ip) 在第5行中,在高阶函数中使用变量ip,会导致异常。我知道使用var是不可取的,但我想知道如何在高阶函数中使用var。或者是否有管理状态的替代方案。以下工作: (1 to 10).foreach(_ => ip += "1")
1 var ip = ArrayBuffer[String]()
2 ip += "1"
3 println(ip)
4 ip.clear()
5 (1 to 10).foreach(ip += ("1"))
6 println(ip)
在第5行中,在高阶函数中使用变量ip
,会导致异常。我知道使用var
是不可取的,但我想知道如何在高阶函数中使用var。或者是否有管理状态的替代方案。以下工作:
(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)
以下工作:
(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)
如果您想走可变路线,只需使用for循环:
for(\如果您想走可变路线,只需使用for循环:for)(_