将项目添加到不可变的Seq [英] Adding an item to an immutable Seq
问题描述
说,我有一个字符串序列作为输入,我想得到一个新的不可变的Seq
,它由输入的元素和项"c"
组成.这是我发现可以使用的两种方法:
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:
-
assert(Seq("a", "b", "c") == Seq("a", "b") ++ Seq("c"))
-这个问题是似乎只是为了操作而实例化一个临时序列(Seq("c")
)是多余的,并且会导致开销 -
assert(Seq("a", "b", "c") == List("a", "b") ::: "c" :: Nil)
-这将输入集合的类型限制为List
,因此Seq("a", "b") ::: "c" :: Nil
将不起作用.同样,实例化Nil
可能也会导致开销
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
我的问题是:
- 还有其他方法可以执行此操作吗?
- 哪个更好?
- 不是不允许
Seq("a", "b") ::: Nil
出现Scala开发人员的漏洞吗?
- 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
:
Use the :+
(append) operator to create a new Seq
using:
val seq = Seq("a", "b") :+ "c"
// seq is now ("a","b","c")
注意::+
将创建一个新的Seq
对象.
如果有
Note: :+
will create a new Seq
object.
If you have
val mySeq = Seq("a","b")
您将致电
mySeq :+ "c"
mySeq
仍为("a","b")
请注意,Seq
的某些实现比其他实现更适合附加. List
已针对前置进行了优化. Vector
具有快速的追加和前置操作.
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.
:::
是List
上的一种方法,它需要另一个List
作为其参数-在接受其他类型的序列时,您看到的优点是什么?它必须将其他类型转换为List
.如果您知道List
对于您的用例有效,那么请使用:::
(如果必须).如果您想要多态行为,请使用通用的++
.
:::
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 ++
.
使用Nil
没有实例化开销;您不要实例化它,因为它是一个单例.
There's no instantiation overhead to using Nil
; you don't instantiate it because it's a singleton.
这篇关于将项目添加到不可变的Seq的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!