Start learning free

LESSON 94 OF 348 · ARRAYS I

Static Array Length in Scala in Scala

Lesson

We can get the length of an array using the .length property like this:

val ourArray = Array(50, 40, 30)

// Printing the length:
println(ourArray.length) // Output: 3

Using the length

We can use the length to access items from the end of an array.

Because arrays are 0-indexed, the index of the last item is length - 1:

val ourArray = Array(50, 40, 30)

// Printing the last item:
println(ourArray(ourArray.length - 1)) // Output: 30

// Printing the second to last item:
println(ourArray(ourArray.length - 2)) // Output: 40

Assignment
Follow the Coding Tutorial and let's play with some arrays.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 3
    Ctrl + Enter to check

    Static Array Length 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