如何在 Scala mutable.Seq 上追加或前置
我对 Scala 的 collection.mutable 有一些不明白的地方。序列
。它描述了所有可变序列的接口,但我没有看到在不创建新序列的情况下附加或前置元素的方法。我在这里遗漏了一些明显的东西吗?
分别有 :+
和 +:
用于追加和前置,但它们创建新的集合 - 我认为是为了与不可变序列的行为保持一致。这很好,但是为什么没有像 +=
和 +=:
这样的方法,就像 ArrayBuffer
和 ListBuffer
一样定义,用于就地附加和前置?这是否意味着如果我想进行就地附加,我无法引用类型为 collection.mutable.Seq
的可变 seq?
再一次,我一定错过了一些明显的东西,但找不到什么......
There's something I don't understand about Scala's collection.mutable.Seq
. It describes the interface for all mutable sequences, yet I don't see methods to append or prepend elements without creating a new sequence. Am I missing something obvious here?
There are :+
and +:
for append and prepend, respectively, but they create new collections — in order to be consistent with the behavior of immutable sequences, I assume. This is fine, but why is there no method like +=
and +=:
, like ArrayBuffer
and ListBuffer
define, for in-place append and prepend? Does it mean that I cannot refer to a mutable seq that's typed as collection.mutable.Seq
if I want to do in-place append?
Again, I must have missed something obvious, but cannot find what…
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
序列的可变性仅保证您能够将项目替换为不同的项目(通过
update
方法),就像使用原始数组一样。它不能保证您能够使序列变得更大(这就是Growable
特征用于)或更小(可收缩
)。缓冲区
是包含Growable
和Shrinkable
的抽象特征,而不是序列
。Mutability for sequences only guarantees that you'll be able to swap out the items for different ones (via the
update
method), as you can with e.g. primitive arrays. It does not guarantee that you'll be able to make the sequence larger (that's what theGrowable
trait is for) or smaller (Shrinkable
).Buffer
is the abstract trait that containsGrowable
andShrinkable
, notSeq
.