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

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

Adding an item to an immutable Seq

listscalaseq

提问by Nikita Volkov

Say, I have a sequence of strings as an input and I want to get a new immutable Seqwhich 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"。以下是我发现有效的两种方法:

  1. 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 overhead
  2. assert(Seq("a", "b", "c") == List("a", "b") ::: "c" :: Nil)- this one restricts the type of input collection to be a List, so Seq("a", "b") ::: "c" :: Nilwon't work. Also it seems that instantiating a Nilmay aswell result in overhead
  1. assert(Seq("a", "b", "c") == Seq("a", "b") ++ Seq("c"))- 这个的问题是,Seq("c")为了操作而实例化一个临时序列 ( )似乎是多余的,会导致开销
  2. assert(Seq("a", "b", "c") == List("a", "b") ::: "c" :: Nil)- 这将输入集合的类型限制为 a List,因此Seq("a", "b") ::: "c" :: Nil不起作用。似乎实例化 aNil也可能导致开销

My questions are:

我的问题是:

  1. Is there any other way of performing this operation?
  2. Which one is better?
  3. Isn't Seq("a", "b") ::: Nilnot being allowed a flaw of Scala's developers?
  1. 有没有其他方法可以执行此操作?
  2. 哪一个更好?
  3. 是不是Seq("a", "b") ::: Nil没有被允许Scala的开发商缺陷?

回答by Ben James

Use the :+(append) operator to create a newSequsing:

使用:+(append) 运算符创建一个新的Seq使用:

val seq = Seq("a", "b") :+ "c"
// seq is now ("a","b","c")

Note: :+will create a new Seqobject. If you have

注意::+将创建一个新Seq对象。如果你有

val mySeq = Seq("a","b")

and you will call

你会打电话

mySeq :+ "c"

mySeqwill still be ("a","b")

mySeq仍然会 ("a","b")

Note that some implementations of Seqare more suitable for appending than others. Listis optimised for prepending. Vectorhas fast append and prepend operations.

请注意, 的某些实现Seq比其他实现更适合附加。List针对前置进行了优化。Vector具有快速追加和前置操作。

:::is a method on Listwhich requires another Listas 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 Listis 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;你不实例化它,因为它是一个单身人士。