将项目添加到不可变的 Seq
假设我有一个字符串序列作为输入,我想获得一个新的不可变的 Seq
,它由输入的元素和一个项目 "c"
组成。以下是我发现有效的两种方法:
- 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
似乎也可能会导致开销
我的问题是:
- 还有其他方法来执行此操作吗?
- 哪一个更好?
- 不允许
Seq("a", "b") ::: Nil
不是 Scala 开发人员的一个缺陷吗?
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"))
- 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
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用
:+
(附加)运算符创建一个newSeq
,使用:注意:
:+
将创建一个新的Seq
对象。如果你有
并且你将调用
mySeq
仍然是("a","b")
请注意,
Seq
的某些实现更合适比其他人追加。List
针对前置进行了优化。Vector
具有快速的追加和前置操作。:::
是List
上的一个方法,它需要另一个List
作为其参数 - 您认为它接受其他类型的优点是什么顺序?它必须将其他类型转换为List
。如果您知道List
对于您的用例来说是有效的,那么请使用:::
(如果必须的话)。如果您想要多态行为,请使用通用的++
。使用
Nil
没有实例化开销;你不实例化它,因为它是一个单例。Use the
:+
(append) operator to create a newSeq
using:Note:
:+
will create a newSeq
object.If you have
and you will call
mySeq
will still be("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.:::
is a method onList
which requires anotherList
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 aList
. If you know thatList
is efficient for your use case then use:::
(if you must). If you want polymorphic behaviour then use the generic++
.There's no instantiation overhead to using
Nil
; you don't instantiate it because it's a singleton.