Scala Arrays by Code Example

Array is a very basic building block of any programming language. Arrays can be treated as static, sequential and fixed size collection of any type in Scala. One important point to note here is ” Scala Arrays are mutable “.

The Syntax of creating array is a bit different than Java and there are two ways to create array in Scala. Let’s have a look.

When you know the type and size of an array and not sure about what are the exact elements in the array,

For Example,

You can see from above code that index Scala array starts from 0.

When you know the type and exactly which elements are present in the array,

In above example you don’t need to specify the type as it can be inferred directly from the element type.

Accessing the elements of an Array
  • arr.length: Returns the size of the Scala array
  • arr(n): This will return element at n index, null if no element is available and ArrayIndexOutOfBoundsException if n is more than arr.length - 1
  • arr(n) = value: This will assign a new value to a respective array element

Multi-dimensional Arrays

Syntax for creating multi-dimensional arrays in Scala is also very different. You have to write import Array._ first.

Here is an simple example of Matrix,

Stay tuned for more examples…..!!!!!

Leave a Reply

Notify of