Scala Lists
A list is an ordered collection of values of the same type. A list cannot be changed after it is created, so a changed list is always a new list.
A list prints exactly as it was created
A list is created with List and round brackets. Printing a list shows the word List and its values in order.
@main def main(): Unit =
val numbers = List(1, 2, 3)
println(numbers)
println(numbers(0))Head gives the first value and tail gives the rest
The head is the first value on its own. The tail is a new list without that first value.
@main def main(): Unit =
val numbers = List(10, 20, 30)
println(numbers.head)
println(numbers.tail)Length and isEmpty describe a list
Length counts the values in a list. isEmpty answers true or false, and an empty list has length 0.
@main def main(): Unit =
val colors = List("red", "blue")
val empty = List()
println(colors.length)
println(colors.isEmpty)
println(empty.isEmpty)
println(empty.length)Example
@main def main(): Unit =
val shopping = List("milk", "eggs", "bread")
println(shopping)
println(shopping.head)
println(shopping.length)
println(shopping.isEmpty)Key points
- Creation: List(1, 2, 3) creates a list that holds the three numbers in order.
- Indexing: xs(0) reads the first value, because positions start at 0.
- Head: xs.head gives the first value in the list.
- Tail: xs.tail gives a new list with every value except the first.
- Length: xs.length gives how many values the list holds.
- Emptiness: xs.isEmpty gives true when the list holds no values.
In this example, the program creates a shopping list with three items and prints the whole list. It then prints the head, which is milk, the length, which is 3, and isEmpty, which is false because the list holds values.
Note
A changed list is always a new list, and the original list stays as it was.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Scastie
Exercise
What does List(5, 6, 7).tail give?