Adding an item to an immutable Seq

雨燕双飞 提交于 2019-12-02 21:01:38
Ben James

Use the :+ (append) operator to create a new Seq using:

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

Note: :+ will create a new Seq object. If you have

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

and you will call

mySeq :+ "c"

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 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 ++.

There's no instantiation overhead to using Nil; you don't instantiate it because it's a singleton.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!