Scala – Array

  • date 6th October, 2020 |
  • by Prwatech |
  • 0 Comments

Guide to Arrays in Scala

 

Arrays in Scala provide a fundamental data structure for storing and accessing a fixed-size sequence of elements. Scala arrays are mutable, allowing elements to be modified after initialization, but their size cannot be changed once created.

To create an array in Scala, you can use the Array object and specify the type of elements along with the initial values. For example:

Scala arrays support various operations like appending elements, updating elements at specific indices, iterating over elements using loops or higher-order functions, and converting to other collection types like List or Seq.

However, Scala encourages the use of higher-level, immutable collections like List or Vector for most scenarios due to their immutability and richer API. Understanding Scala arrays is essential for working with low-level data manipulation and interfacing with Java libraries that use arrays extensively.

Array:

The array, which stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.

·        Array is a collection of similar elements

Maintains Insertion Order

·        Immutable

. Once Array is defined, we cannot grow or shrink their size

. However we may change their index

Array is classified into:

. 1-D Array

2-D Array

·   Multi-D Array

Program to Display 1-D Array using Concatenation:

package Collection
import Array._
  object A1
  {
    def main(args: Array[String])
    {
      var arr1 = 

#Array

(1, 2, 3, 4)
      var arr2 = 

Array

(5, 6, 7, 8)

      var arr3 = 

concat

( arr1, arr2)
      for(x <- arr3)
      {
        

println

( x )
      }
    }
  }

Program to Display Multidimensional Array :

package Collection

 

object MultiArr
{
def main(args: Array[String])
{
val arr = Array(Array(2, 4, 6, 8, 10),
Array(1, 3, 5, 7, 9))

for(i<-0 to 1)
{
for(j<- 0 to 4)
{
print(" "+arr(i)(j))
}
println()
}
}
}

 

Guide to Arrays in Scala

Quick Support

image image