gpt4 book ai didi

list - scala 可变 val 列表

转载 作者:行者123 更新时间:2023-12-04 12:05:54 25 4
gpt4 key购买 nike

几天前,我找到了 Paul Philip 的要点 https://gist.github.com/paulp/9085746这显示出非常奇怪的行为。
我没有找到任何解释这怎么可能

简化的代码片段:

val buf = new ListBuffer[Int]()
buf ++= Seq(1,2,3)
val lst: List[Int] = buf.toIterable.toList
println(lst) //List(1,2,3)
buf ++= Seq(4,5,6)
println(lst) //List(1,2,3,4,5,6)

它在没有 toIterable 的情况下按预期工作
val buf = new ListBuffer[Int]()
buf ++= Seq(1,2,3)
val lst: List[Int] = buf.toList
println(lst) //List(1,2,3)
buf ++= Seq(4,5,6)
println(lst) //List(1,2,3)

那里发生了什么?

最佳答案

如果您查看 List source ,你会看到缺点 ::类的尾部定义为 private[scala] var tl不是 val ,所以它在内部是可变的。

这种突变正在发生 during ListBuffer append除非 exported标志已设置。

此标志在 the toList method 中设置,防止进一步修改相同的 List
但是toIterable继承自 SeqForwarder -> IterableForwarder ,它不知道这样的事情,但返回相同的 start对象 as it used as underlying value

关于list - scala 可变 val 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35491233/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com