Scala Arrays Example

Filed Under: Scala

Scala supports the array data structure. An array is a fixed size data structure that stores elements of the same data type. The index of first element of an array is zero and the last element is the total number of elements minus one.

Scala Array Declaration

The syntax for declaring an array variable is


var arrayname = new Array[datatype](size)

var indicates variable and arrayname is the name of the array, new is the keyword, datatype indicates the type of data such as integer, string and size is the number of elements in an array.

For example,


var student = new Array[String](5)

Or 

var student:Array[String] = new Array[String](5)

Here student is a string array that holds five elements. Values can be assigned to an array as below.


var student = Array("John","Adam","Rob","Reena","Harry")

or 

student(0) = "Martin" ; student(1) = "Jack" ; student(2) = "Jill" ; student(3) = "Paul" ; student(4) = "Kevin"

Scala Arrays Processing

While processing arrays we use for loop as the elements are of same data type.

Consider an example below.


object Student {
   def main(args: Array[String]) {
      var marks = Array(75,80,92,76,54)
      
      println("Array elements are : ")
        for ( m1 <- marks ) {
         println(m1 )
      }
         
      var gtot = 0.0
      for ( a <- 0 to (marks.length - 1)) {
         gtot += marks(a);
      }
      println("Grand Total : " + gtot);

 var average = 0.0
 average = gtot/5;
 println("Average : " + average);
}
}

Here we are creating marks array of Integer data type. We are printing the elements of an array using for loop. We are calculating the total marks by adding all the elements and calculate average by dividing the total by the number of subjects.

Below image shows the execution of above program.

Scala-Arrays-Example

Scala Multi Dimensional Arrays

Multidimensional arrays can be defined as an Array whose elements are arrays.

Consider an example below.


object Multidim {
def main(args:Array[String]) {
   val rows = 2
   val cols = 3
   val multidim = Array.ofDim[String](rows,cols)
   multidim(0)(0) = "Reena"
   multidim(0)(1) = "John"
   multidim(0)(2) = "Adam"
   multidim(1)(0) = "Michael"
   multidim(1)(1) = "Smith"
   multidim(1)(2) = "Steve"
   for {
   i <- 0 until rows
   j <- 0 until cols
 }
 println(s"($i)($j) = ${multidim(i)(j)}")
 }
}

We are creating a two dimensional array with 2 rows and 3 columns using the ofDim method which accepts rows and columns as arguments. Add the elements to the array as rows and columns accepting string arguments. We are using for loop retrieve the inserted elements.

Save the above code in Multidim.scala and run as shown in below image.

Scala-Multi-Dimensional-Array

Scala Concatenate Arrays

Two arrays can be concatenated using the concat method. Array names can be passed as an argument to the concat method.

Below is an example showing how to concatenate two arrays.


import Array._

object Student {
   def main(args: Array[String]) {
      var sname = Array("John","Adam","Rob","Reena","Harry")      
      var sname1 = Array("Jack","Jill","Henry","Mary","Rohan")

      var names =  concat( sname, sname1)
      println("Student name array elements are  : ");
        for ( n1 <- names ) {
         println( n1 )
      }
   }
}

We have to use import Array._ since the array methods concat is defined in the package. We have declared two arrays sname and sname1 having student names as the elements. We are concatenating these two arrays using concat method and passing sname and sname1 as arguments and storing the resultant elements in names array.

Save the code in Student.scala and then compile and run as shown in below image.

Scala-Array-Concat-Example

Scala Array with range

The range() method generates an array containing sequence of integers. The final argument is used as a step to generate the sequence of integers. If the argument is not specified then the default value assumed is 1.

Let us understand this range method through an example.


import Array._

object Student {
   def main(args: Array[String]) {
      var id = range(7, 23, 3)
      var age = range(15,20)
      for ( s <- id ) {
         print( " " + s)
      }
      println()
      for ( a <- age ) {
         print( " " + a )
      }
   }
}

We are declaring arrays id and age and generating the elements using range method. The elements start from 7 to 23 incrementing by 3. For the age the increment value by 1 starting from 15 until 20.

Run the above code by typing Student.main(null) and you will see below output.


7 10 13 16 19 22
 15 16 17 18 19

Before I conclude the post, below are some useful Array methods:

  1. def concat[T]( xss: Array[T]* ): Array[T]: Concatenates all arrays into a single array
  2. def empty[T]: Array[T]: Returns an array of length 0
  3. def ofDim[T]( n1: Int, n2: Int ): Array[Array[T]]: Creates a 2-dimensional array
  4. def range( start: Int, end: Int, step: Int ): Array[Int]: Returns an array containing equally spaced values in some integer interval
  5. def copy( src: AnyRef, srcPos: Int, dest: AnyRef, destPos: Int, length: Int ): Unit: Copy one array to another
  6. def ofDim[T]( n1: Int, n2: Int, n3: Int ): Array[Array[Array[T]]]: Creates a 3-dimensional array

That’s all for arrays in Scala programming, we will look into other scala features in future posts.

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages