如何在 Scala mutable.Seq 上附加或前置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6626238/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 03:11:00  来源:igfitidea点击:

How to append or prepend on a Scala mutable.Seq

scalasequencescala-collectionsmutable

提问by Jean-Philippe Pellet

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?

关于 Scala 的collection.mutable.Seq. 它描述了所有可变序列的接口,但我没有看到在不创建新序列的情况下附加或添加元素的方法。我在这里遗漏了一些明显的东西吗?

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 ArrayBufferand ListBufferdefine, for in-place append and prepend? Does it mean that I cannot refer to a mutable seq that's typed as collection.mutable.Seqif I want to do in-place append?

分别有:++:for append 和 prepend,但它们创建新的集合——为了与不可变序列的行为保持一致,我假设。这很好,但为什么没有像+=and +=:、 likeArrayBufferListBufferdefine这样的方法来进行就地追加和前置?这是否意味着我不能引用一个可变的 seq,它的类型就像collection.mutable.Seq我想做就地追加一样?

Again, I must have missed something obvious, but cannot find what…

再说一次,我一定漏掉了一些明显的东西,但找不到什么……

回答by Rex Kerr

Mutability for sequences onlyguarantees that you'll be able to swap out the items for different ones (via the updatemethod), as you can with e.g. primitive arrays. It does notguarantee that you'll be able to make the sequence larger (that's what the Growabletrait is for) or smaller (Shrinkable).

序列的可变性保证您能够将项目交换为不同的项目(通过update方法),就像您可以使用原始数组一样。它不能保证您能够使序列更大(这就是Growable特征的用途)或更小 ( Shrinkable)。

Bufferis the abstract trait that contains Growableand Shrinkable, not Seq.

Buffer是包含Growable和的抽象特征,而Shrinkable不是Seq