将项目添加到不可变的Seq [英] Adding an item to an immutable Seq

查看:77
本文介绍了将项目添加到不可变的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:

  1. assert(Seq("a", "b", "c") == Seq("a", "b") ++ Seq("c"))-这个问题是似乎只是为了操作而实例化一个临时序列(Seq("c"))是多余的,并且会导致开销
  2. assert(Seq("a", "b", "c") == List("a", "b") ::: "c" :: Nil)-这将输入集合的类型限制为List,因此Seq("a", "b") ::: "c" :: Nil将不起作用.同样,实例化Nil可能也会导致开销
  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" :: Nil won't work. Also it seems that instantiating a Nil may aswell result in overhead

我的问题是:

  1. 还有其他方法可以执行此操作吗?
  2. 哪个更好?
  3. 不是不允许Seq("a", "b") ::: Nil出现Scala开发人员的漏洞吗?
  1. Is there any other way of performing this operation?
  2. Which one is better?
  3. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆