Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

scala
size
array
communitycreator

How to get the size of an array in Scala

Theodore Kelechukwu Onyejiaku

Overview

We can get the size of an array using the size property. Array size is the number of elements that an array contains. It is similar to the length property.

Syntax

array.size
Syntax for size of an array in Scala

Return

The value returned is an integer value that represents the number of elements present in the array.

Code

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)

    // get and print there sizes
    println(randomNumbers.size)
    println(fruits.size)
    println(cgpas.size)
}
Get the size of an array in Scala

Explanation

  • Lines 3–5: We create some arrays in Scala and initialize them with some values.
  • Lines 8–10: We get the size of the arrays using the size property. We then print the values to the console.

RELATED TAGS

scala
size
array
communitycreator

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku
RELATED COURSES

View all Courses

Keep Exploring