In Scala, a List stores multiple values in one variable. Lists keep their elements in order and use zero-based indexing, so the first element is at index 0.
Creating a List:
val sandwich = List("peanut butter", "jelly", "bread")
Accessing elements:
val numbers = List(50, 60, 70)
val data = numbers(1)
// data is 60
Indexing with ():
Scala indexes collections with parentheses, not square brackets — write numbers(0), not numbers[0]. The same applies to a fixed-size Array, which you create with Array(...):
val arr = Array(1, 2, 3)
val first = arr(0) // 1 — use (), not arr[0]
That's the numbers(1) style you see throughout the coding tutorials.
Getting the size:
println(numbers.size)
Iterating:
for (ingredient <- sandwich) {
println(ingredient)
}
When you need a list that can be changed, Scala also has scala.collection.mutable.ArrayBuffer.
Assignment
Follow the Coding Tutorial and let's create some lists.
Hint
Use List(...) to create a Scala list.
Free plan: 30 tutor messages. Premium is unlimited.