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 arraysval 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 arraysprintln(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
lengthproperty and then print these lengths to the console.