scala - 在高阶函数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。或者是否有管理状态的替代方法。
解决方案
以下作品:
(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)
推荐阅读
- bash - ׁׁׁׁ如何将值从 bash 文件返回到 jenkinsfile?
- python - 我如何对新字典 python 进行排序
- database - 数据库架构 - 结构数据
- python - Python解密字节并将它们作为字符串保存在列表中
- javascript - “类”和“功能组件”中的逻辑相同但行为不同
- python - 我的不和谐 get() 方法有什么问题?
- makefile - make :在 VS 代码中无法识别术语“make”
- python - 如何将单个元组传递给需要元组元组的函数
- javascript - 重叠路由在 Koa.js 中不起作用
- c++ - 我如何做可变参数的可变参数模板