Datalieve Image Logo

Scala How to create and add an element to List

If you are new to Scala and using Ubuntu, check out the article to install Scala on Ubuntu in the previous post.

Let’s come back to our original topic on how to create and add an element to Scala list.

Hmm!.. This may be a straightforward thing in other programming languages, but not is Scala.

Didn’t cover creating a list separately, you can be seen in the below code snippets. You can’t add an element to a List because in Scala, Lists are immutable data structure means you can’t change the data structures once they were initialized. But you can concatenate or add or append two lists into a single list. The actual question should be How to add an element to ListBuffer :-).

ListBuffer are the mutable version of the List. So let’s quickly work on lists and then go to ListBuffers.

Hence, we can’t directly add elements to list, let’s see how to add elements indirectly?

scala> val a = List(1)
a: List[Int] = List(1)

scala> val b = List(2)
b: List[Int] = List(2)

scala> val c = a ++ b
c: List[Int] = List(1, 2)

scala> val d = b ++ a
d: List[Int] = List(2, 1)

List initialization ss

Let me explain the code in the above screenshot.

In the first statement we are initializing a List named a which contains an integer 1.

Next we are initializing another List named b which contains an integer 2.

Then, we are creating a List of integers by concatenating List a and List b using ++ operator. Since we used List a followed by List b the new list contain all the elements of List a in the first position and List b in the second position. In the fourth statement you can see List b followed by List a and the same can be seen in the result.

How to add/append elements to ListBuffer?

import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ListBuffer

scala> val a = new ListBuffer[Int]()
a: scala.collection.mutable.ListBuffer[Int] = ListBuffer()

scala> a += 1
res0: a.type = ListBuffer(1)

Creation of listbuffer

If you are using Scala RELP you should know the exact package where ListBuffer is present. If an IDE, you should be relieved since the IDE will be taking care of the imports, but it’s good to know in which packages the classes are present. After importing, we have initialized an empty ListBuffer named as a. Then, we have added an element to the ListBuffer.

scala> a += 2
res2: a.type = ListBuffer(1, 2)

ListBuffer addition of elements

Similarly, we have added one more element, 2 to the ListBuffer. 

Feel free to comment below for question and clarifications.

© 2022, Datalieve . All rights reserved.

Leave a Reply

Your email address will not be published. Required fields are marked *

You cannot copy content of this page