7

Few days ago I found Paul Philip’s gist https://gist.github.com/paulp/9085746 which shows quite strange behavior. I did not find any explanation how is that possible

simplified code snippet:

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)

It works as expected without 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)

What is going on there?

4

1 回答 1

6

如果您查看Listsource,您会看到 cons::类的尾部定义为private[scala] var tlnot val,因此它在内部是可变的。

除非设置了标志,否则此突变ListBuffer追加期间发生。exported

该标志在方法中设置toList防止进一步修改相同的List

但是是从->toIterable继承的,它不知道这样的事情,但返回的对象与它用作 值的对象相同SeqForwarderIterableForwarderstartunderlying

于 2016-02-18T20:30:13.207 回答