How to get the length of an array in Scala

Overview

We can get the length of an array in Scala by using the length property. The length property returns the length of an array in Scala.

Syntax

array.length
length property syntax in Scala

Return value

An integer that represents the number of elements in an array.

Code example

object Main extends App {
// create some arrays
val randomNumbers = Array(34, 2, 5, 70, 1)
val fruits = Array("Pineapple", "Banana", "Orange")
val cgpas : Array[Double] = Array(3.4, 4.5, 2.5, 0.5)
val names = new Array[String](3)
names(0) = "Amara"
names(1) = "Funke"
names(2) = "Ade"
// print length of arrays
println(randomNumbers.length)
println(fruits.length)
println(cgpas.length)
println(names.length)
}

Explanation

  • Lines 3–10: We create arrays using different methods that are available in Scala.
  • Lines 13–16: We obtain the lengths of the arrays by using the length property and then print these lengths to the console.

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources