Skip to content
Related Articles

Related Articles

Scala | Arrays
  • Last Updated : 11 Mar, 2019

Array is a special kind of collection in scala. it is a fixed size data structure that stores elements of the same data type. The index of the first element of an array is zero and the last element is the total number of elements minus one. It is a collection of mutable values. It corresponds to arrays(in terms of syntax) in java but at the same time it’s different(in terms of functionalities) from java.

Some Important Points:

  • Scala arrays can be generic. which mean we can have an Array[T], where T is a type parameter or abstract type.
  • Scala arrays are compatible with Scala sequences – we can pass an Array[T] where a Seq[T] is required.
  • Scala arrays also support all sequence operations.

The following figure shows how values can be stored in array sequentially :
Arrays

Scala supports both one as well as multi-dimension arrays. A single dimension array is one having only one row and n columns whereas two dimension array is actually a matrix of dimension (n * m).

One Dimensional Array

In this array contains only one row for storing the values. All values of this array are stored contiguously starting from 0 to the array size.
Syntax:



var arrayname = new Array[datatype](size)

Here, datatype specifies the type of data being allocated, size specifies the number of elements in the array, and var is the name of array variable that is linked to the array.
Example:




// Scala program to creating an array 
// of the string as week days, store  
// day values in the weekdays, 
// and prints each value. 
object GFG
{
    // Main method
    def main(args: Array[String]) 
    {
        // allocating memory of 1D Array of string. 
        var days = Array("Sunday", "Monday", "Tuesday"
                    "Wednesday", "Thursday", "Friday",
                    "Saturday" )
      
        println("Array elements are : ")
        for ( m1 <-days )
        {
            println(m1 )
        }
          
    }
}
Output:
Array elements are : 
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday

Here, we are creating an array to store the days of the week and printing all days.

Basic Operation On An Array
  1. Accessing array elements:
    Example:




    // Scala program to accessing an array 
    // of the string as name.
    object GFG
    {
        // Main method
        def main(args: Array[String]) 
        {
            // allocating memory of 1D Array of string. 
            var name = Array("gfg", "geeks", "GeeksQuize"
                        "geeksforgeeks" )
          
            println("second element of an array is: ")
              
            // Accessing an array element
            println(name(1) )
        }
    }

    Output:

    second element of an array is: 
    geeks
  2. Updating an element in array:
    Example:




    // Scala program to updating an array 
    // of the string as name.
    object GFG
    {
        // Main method
        def main(args: Array[String]) 
        {
            // allocating memory of 1D Array of string. 
            var name = Array("gfg", "geeks", "GeeksQuize"
                        "geeksforgeeks" )
                          
            // Updating anelement in an array             
            name(1)="employee"
            println("After updation array elements are: ")
              
            for ( m1 <-name )
            {
                println(m1 )
            }
        }
    }

    Output:

    After updation array elements are: 
    gfg
    employee
    GeeksQuize
    geeksforgeeks
  3. Adding elements in an array:
    Example:






    // Scala program to adding elements in an array 
    // of the string as name.
    object GFG
    {
        // Main method
        def main(args: Array[String]) 
        {
            var name = new Array[String](4)
              
            // Adding element in an array 
            name(0)="gfg"
            name(1)="geeks"
            name(2)="GeeksQuize"
            name(3)="geeksforgeeks"
            println("After adding array elements : ")
              
            for ( m1 <-name )
            {
                println(m1 )
            }
          
        }
    }

    Output:

    After adding array elements : 
    gfg
    geeks
    GeeksQuize
    geeksforgeeks
  4. Concatenate Arrays:
    We can concatenate two arrays by using concat() method. In concat() method we can pass more than one array as arguments.
    Example:




    // Scala program to concatenate two array 
    // by using concat() method
    import Array._
      
    // Creating object
    object GFG
    {
          
        // Main method
    def main(args: Array[String])
    {
        var arr1 = Array(1, 2, 3, 4)
        var arr2 = Array(5, 6, 7, 8)
      
        var arr3 = concat( arr1, arr2)
          
        // Print all the array elements
        for ( x <- arr3
        {
            println( x )
        }
    }
    }

    Output:

    1
    2
    3
    4
    5
    6
    7
    8

    Here, arr1 is an array of four elements and arr2 is another array of four elements now we concatenate these two array in arr3 by using concat() method.

Multidimensional Arrays

The Multidimensional arrays contains more than one row to store the values. Scala has a method Array.ofDim to create Multidimensional arrays in Scala . In structures like matrices and tables multi-dimensional arrays can be used.
Syntax:

var array_name = Array.ofDim[ArrayType](N, M)
 or  
var array_name = Array(Array(elements), Array(elements)

This is a Two-Dimension array. Here N is no. of rows and M is no. of Columns.

Example:




// Scala program to creating a 
// multidimension array of the 
// string as names, store  
// values in the names, 
// and prints each value. 
object GFG
{
    // Main method
    def main(args:Array[String]) 
    {
        val rows = 2
        val cols = 3
          
        // Declaring Multidimension array
        val names = Array.ofDim[String](rows, cols)
          
        // Allocating values
        names(0)(0) = "gfg"
        names(0)(1) = "Geeks"
        names(0)(2) = "GeeksQuize"
        names(1)(0) = "GeeksForGeeks"
        names(1)(1) = "Employee"
        names(1)(2) = "Author"
        for
        {
            i <- 0 until rows
            j <- 0 until cols
        }
          
        // Printing values
        println(s"($i)($j) = ${names(i)(j)}")
    }
}
Output:
(0)(0) = gfg
(0)(1) = Geeks
(0)(2) = GeeksQuize
(1)(0) = GeeksForGeeks
(1)(1) = Employee
(1)(2) = Author
Append and Prepend elements to an Array in Scala

Use these operators (methods) to append and prepend elements to an array while assigning the result to a new variable:

MethodFunctionExample
:+append 1 itemold_array :+ e
++append N itemold_array ++ new_array
+:prepend 1 iteme +: old_array
++:prepend N itemsnew_array ++: old_array

Examples to show how to use the above methods to append and prepend elements to an Array:




object GFG
{
     
  // Main method
  def main(args: Array[String])
  {
      
    // Declaring an array
    val a = Array(45, 52, 61
    println("Array a ")
    for ( x <- a ) 
    {
      println( x )
    }
  
    // Appending 1 item
    val b = a :+ 27 
    println("Array b ")
    for ( x <- b ) 
    {
      println( x )
    }
  
    // Appending 2 item
    val c = b ++ Array(1, 2)
    println("Array c ")
    for ( x <- c ) 
    {
       println( x )
    }
  
    // Prepending 1 item
    val d = 3 +:
    println("Array d ")
    for ( x <- d ) 
    {
      println( x )
    }
  
    // Prepending 2 item
    println("Array e ")
    val e = Array(10, 25) ++: d
    for ( x <- e ) 
    {
      println( x )
    }
  }
}

Output :

Array a 
45
52
61
Array b 
45
52
61
27
Array c 
45
52
61
27
1
2
Array d 
3
45
52
61
27
1
2
Array e 
10
25
3
45
52
61
27
1
2
My Personal Notes arrow_drop_up
Recommended Articles
Page :