Soatl
Soatl

Reputation: 10592

Appending to a list in Scala

I have no clue why Scala decided to make this such a chore, but I simply want to add an item to a list

var previousIds: List[String] = List()

I have tried the following:

previousIds ::: List(dataListItem.id)
previousIds :: List(dataListItem.id)
previousIds :+ List(dataListItem.id)
previousIds +: List(dataListItem.id)
previousIds :+ dataListItem.id
previousIds +: dataListItem.id

In every one of these instances, the line will run but the list still will contain 0 items

When I try to add a new list:

val list = List[String](dataListItem.id)
previousIds += list

I get an error that list needs to be a string. When I add a string

previousIds += dataListItem.id

I get an error that it needs to be a list

For some reason, the only thing that will work is the following:

previousIds :::= List[String](dataListItem.id)

which seems really excessive, since, adding to a list should be a trivial option. I have no idea why nothing else works though.

How do you add an item to a list in scala (that already exists) without having to make a new list like I am doing?

Upvotes: 0

Views: 65

Answers (2)

jrook
jrook

Reputation: 3519

Use MutableList

scala> var a = scala.collection.mutable.MutableList[String]()
a: scala.collection.mutable.MutableList[String] = MutableList()

scala> a += "s"
res0: scala.collection.mutable.MutableList[String] = MutableList(s)

scala> a :+= "s"

scala> a
res1: scala.collection.mutable.MutableList[String] = MutableList(s, s)

Upvotes: 1

Pavel
Pavel

Reputation: 1539

Next code should help you for a start. My assumption you are dealing with mutable collections:

val buf = scala.collection.mutable.ListBuffer.empty[String]

buf += "test"

buf.toList

In case you are dealing with immutable collections next approach would help:

val previousIds = List[String]("A", "TestB")

val newList = previousIds :: List("TestB")

Please refer to documentation for mode details:

http://www.scala-lang.org/api/current/scala/collection/immutable/List.html

Upvotes: 1

Related Questions