How do I add elements to a Scala List?

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.

转载于:https://www.cnblogs.com/seaspring/p/5645222.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值