Open In App

How to Add Element in an Immutable Seq in Scala?

Last Updated : 02 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will learn how to add elements in immutable seq in Scala. immutable sequences, such as List, cannot have elements added to them directly because they are designed to be immutable.

However, you can create a new sequence with an additional element by using methods like :+ (for appending) or +: (for prepending), which returns a new sequence with the added element.

Syntax:

  • For Appending: originalList :+ 4
  • For Prepending: 0 +: originalList

Example 1:

Below is the Scala program to add numbers in an immutable sequence:

Scala
// Original immutable sequence
val originalList = List(1, 2, 3)

// Adding an element to the end of the sequence
val modifiedList = originalList :+ 4

// Adding an element to the beginning of the sequence
val modifiedList2 = 0 +: originalList

// Printing modified lists
println(modifiedList)  
println(modifiedList2) 

Output:

7

Explanation:

  1. :+ appends an element to the end of the list.
  2. +: prepends an element to the beginning of the list.

Example 2:

Below is the Scala program to add words in an immutable sequence:

Scala
// Original immutable sequence
val originalSeq = Seq("apple", "banana", "orange")

// Adding an element to the end of the sequence
val modifiedSeq = originalSeq :+ "grape"

// Adding an element to the beginning of the sequence
val modifiedSeq2 = "melon" +: originalSeq

// Printing modified sequences
println(modifiedSeq)  
println(modifiedSeq2) 

Output:

8

Explanation:

  1. :+ appends an element to the end of the sequence.
  2. +: prepends an element to the beginning of the sequence.

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads