Scala List Operations
List operations are methods that build a new list from an existing list. The original list stays exactly as it was after every operation.
:: adds to the front and ++ joins two lists
The :: operator places one value at the front of a list. The ++ operator joins two lists into one longer list.
@main def main(): Unit =
val numbers = List(2, 3)
val started = 1 :: numbers
val joined = started ++ List(4, 5)
println(started)
println(joined)
println(numbers)sorted, reverse and distinct each return a new list
These methods reorder or clean up a list in different ways. The last line proves the original list did not change.
@main def main(): Unit =
val numbers = List(3, 1, 2, 1)
println(numbers.sorted)
println(numbers.reverse)
println(numbers.distinct)
println(numbers)take, drop, sum, min, max and contains answer questions about a list
take and drop return shorter lists from the front of a list. The other methods give one number or one true or false answer.
@main def main(): Unit =
val numbers = List(5, 2, 8, 4)
println(numbers.take(2))
println(numbers.drop(2))
println(numbers.sum)
println(numbers.min)
println(numbers.max)
println(numbers.contains(8))Example
@main def main(): Unit =
val scores = List(70, 90, 80)
val ordered = scores.sorted
println(ordered.mkString(", "))
println(scores.sum)
println(60 :: ordered)
println(scores)Key points
- Front add: 0 :: xs returns a new list with 0 added at the front.
- Joining: xs ++ ys returns a new list that holds the values of both lists.
- Ordering: xs.sorted returns a new list with the values in increasing order.
- Reversing: xs.reverse returns a new list with the values in the opposite order.
- Taking: xs.take(2) returns a new list with only the first two values.
- Totals: xs.sum adds up all the numbers in a list of numbers.
In this example, the program sorts the scores into a new list and joins that list into text with mkString. It prints the sum of the original scores, then a new list with 60 added at the front, and finally the original list to show it never changed.
Note
Every operation in this lesson returns a new list and leaves the original list unchanged.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Scastie
Exercise
What does List(3, 1, 2).sorted give?