list 将项目添加到不可变的 Seq
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8295597/
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
Adding an item to an immutable Seq
提问by Nikita Volkov
Say, I have a sequence of strings as an input and I want to get a new immutable Seq
which consists of elements of the input and an item "c"
. Here are two methods that I've discovered to be working:
说,我有一个字符串序列作为输入,我想获得一个新的不可变Seq
元素,它由 input 元素和 item 组成"c"
。以下是我发现有效的两种方法:
assert(Seq("a", "b", "c") == Seq("a", "b") ++ Seq("c"))
- the problem with this one is that it seems that instantiating a temporary sequence (Seq("c")
) just for the sake of the operation is rendundant and will result in overheadassert(Seq("a", "b", "c") == List("a", "b") ::: "c" :: Nil)
- this one restricts the type of input collection to be aList
, soSeq("a", "b") ::: "c" :: Nil
won't work. Also it seems that instantiating aNil
may aswell result in overhead
assert(Seq("a", "b", "c") == Seq("a", "b") ++ Seq("c"))
- 这个的问题是,Seq("c")
为了操作而实例化一个临时序列 ( )似乎是多余的,会导致开销assert(Seq("a", "b", "c") == List("a", "b") ::: "c" :: Nil)
- 这将输入集合的类型限制为 aList
,因此Seq("a", "b") ::: "c" :: Nil
不起作用。似乎实例化 aNil
也可能导致开销
My questions are:
我的问题是:
- Is there any other way of performing this operation?
- Which one is better?
- Isn't
Seq("a", "b") ::: Nil
not being allowed a flaw of Scala's developers?
- 有没有其他方法可以执行此操作?
- 哪一个更好?
- 是不是
Seq("a", "b") ::: Nil
没有被允许Scala的开发商缺陷?
回答by Ben James
Use the :+
(append) operator to create a newSeq
using:
使用:+
(append) 运算符创建一个新的Seq
使用:
val seq = Seq("a", "b") :+ "c"
// seq is now ("a","b","c")
Note: :+
will create a new Seq
object.
If you have
注意::+
将创建一个新Seq
对象。如果你有
val mySeq = Seq("a","b")
and you will call
你会打电话
mySeq :+ "c"
mySeq
will still be ("a","b")
mySeq
仍然会 ("a","b")
Note that some implementations of Seq
are more suitable for appending than others. List
is optimised for prepending. Vector
has fast append and prepend operations.
请注意, 的某些实现Seq
比其他实现更适合附加。List
针对前置进行了优化。Vector
具有快速追加和前置操作。
:::
is a method on List
which requires another List
as its parameter - what are the advantages that you see in it accepting other types of sequence? It would have to convert other types to a List
. If you know that List
is efficient for your use case then use :::
(if you must). If you want polymorphic behaviour then use the generic ++
.
:::
是一种List
需要另一个List
作为其参数的方法 - 您在它接受其他类型的序列时看到的优势是什么?它必须将其他类型转换为List
. 如果您知道这List
对您的用例有效,则使用:::
(如果必须)。如果您想要多态行为,请使用泛型++
.
There's no instantiation overhead to using Nil
; you don't instantiate it because it's a singleton.
使用没有实例化开销Nil
;你不实例化它,因为它是一个单身人士。