Start learning free

LESSON 89 OF 348 · ARRAYS I

Lists in Scala in Scala

Lesson

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.


STEP 1 OF 2
    Ctrl + Enter to check

    Arrays in Scala

    Keep going with ScalaAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free