Scala Lists - chrisbitm/python GitHub Wiki
Lists in Scala are immutable. This means that you cannot make changes to it. You also cannot delete elements from it.
val lst1 = List(1,2,3)
println(lst1)
Adding to the List
You have to assign a new List to a Variable in order to add Elements to it.
Prepend
val lst1 = List(1,2,3)
val lst2 = 0 +: lst1
println(lst1)
println(lst2)
- Use the
+:
to add
If you want to add
You can also use the ::
to Concatenate multiple Expressions together.
val lst2 = List(2,3,4);
val lst3 = List(5,6,7);
val lst4 = List(0,1);
val lst1 = lst4 :: lst2 :: lst3;
println(lst1);
Or, you can just add an individual Element.
val list = List(2, 3, 4)
val result = 1 :: list
// Output: List(1, 2, 3, 4)
println(reslut)
Append
val lst1 = List(1,2,3)
val lst2 = lst1 :+ 4
val lst3 = 0 +: lst2
println(lst1)
println(lst2)
println(lst3)
You can also use the ++
Operator to combine (Or Concatenate) multiple Lists into one.
val lst1 = List(1,2,3)
val lst2 = List(4,5,6)
val lst3 = List(7,8,9)
val lst4 = lst1 ++ lst2 ++ lst3
println(lst4)
In the above example, notice where the +
symbol is positioned in the code. That is hint on remembering the structure when it comes to Prepending versus Appending Elements.