How to Add Element in an Immutable Seq in Scala?
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:
// 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:
Explanation:
:+
appends an element to the end of the list.+:
prepends an element to the beginning of the list.
Example 2:
Below is the Scala program to add words in an immutable sequence:
// 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:
Explanation:
:+
appends an element to the end of the sequence.+:
prepends an element to the beginning of the sequence.
Contact Us