Array In Scala

Learn via video courses
Topics Covered

Overview

Arrays form a fundamental part of Scala programming, enabling us to organize and manipulate collections of elements efficiently. Array in Scala is a fixed-size, mutable data structure that can hold elements of the same type. The array represents a collection of elements in a specific order, where each element possesses an index corresponding to its position hence providing random access to their elements based on an index.

Introduction

Array in Scala represents a contiguous block of memory, where elements are stored in a specific order. An array can only hold elements of the same type. This ensures type safety and efficient memory allocation. Elements in an array are accessed using indices, allowing for direct random access. Array indices start from 0 and increment sequentially.

Declaring Array Variables

In Scala, we can declare array variables using the Array class. In Scala, we can use val to declare an immutable array variable or var to declare a mutable array variable.

  • Immutable Arrays: It cannot be reassigned to a different array object but can have their elements modified.
  • Mutable Arrays It can be reassigned to a different array object and have their elements modified.
    It's important to specify the data type of the array when declaring the variable, as the array in Scala is homogeneous and can only store elements of the same type.

Declaring Array Variables

Syntax:

Here is the syntax of how we can declare array variables in Scala:

Declaring an empty array variable with a specified type:

In the above syntax, arr is declared as an empty array of type Int with a size of 5. The new Array[Int](5) expression creates a new array object with the specified size.

Declaring an array variable with initial values:

In the above syntax, fruits is declared as an array of type String with initial values "Apple", "Banana", and "Orange". The Array("Apple", "Banana", "Orange") expression creates a new array and initializes it with the specified elements.

Command:

Individual elements can be assigned values or accessed by utilizing commands like the following.

Assigning values to the array variable arr:

Here, the values 10, 20, and 50 are assigned to the first, second and third elements of array arr respectively.

Accessing values in fruits array:

Here, we have accessed the first and third elements of the array fruits by directly specifying their indices.

Processing Arrays

Processing array in Scala involves various operations such as iterating over elements, modifying values, performing transformations, filtering elements, aggregating data, and more. Processing of an array in Scala is done using the loop statements and iterating over the elements sequentially.

Example:

Let's see an example to demonstrate the processing of different operations in an array in Scala.

Output:

Explanation:

  • In the above example, we define an object named ArrayProcessingExample with a main method. Inside the main method, we declare an array (array) with elements [10, 5, 8, 2, 15].
  • To iterate over the array, we use a loop with an index variable (index). We print each element by accessing it using the index: val element: Int = array(index).
  • To calculate the average, we use a loop to iterate over the array of elements and accumulate the sum of all elements. Then we divide the sum by the length of the array to obtain the average.
  • To find the smallest element, we initialize a variable (smallestElement) with the first element of the array. Then we iterate over the remaining elements using a loop, comparing each element with the current smallest element and updating it if a smaller element is found.
  • Finally, we print the average and the smallest element.

Multi-Dimensional Arrays

In Scala, multidimensional arrays are arrays of arrays, where each element in the outer array is itself an array. This allows you to create arrays with multiple dimensions, such as 2D arrays (arrays with rows and columns) or higher-dimensional arrays.

Multi-Dimensional Arrays

Scala supports the creation and manipulation of multidimensional arrays using nested arrays or the Array.ofDim method.

  • Creating multidimensional array in Scala using nested arrays:
  • Creating multidimensional array in Scala Using Array.ofDim:

Example:

Let's see an example to understand the multidimensional array in Scala:

Output:

Explanation:

  • In this above example, we use the Array.ofDim method to create a 2D array named matrix with dimensions 3x3. The method Array.ofDim[Int](3, 3) creates an Array[Array[Int]] with three rows and three columns, initializing all elements to their default value (0 in the case of Int).
  • We then assign values to the elements of the 2D array using a for loop. Each element is accessed using the row and column indices and assigned the desired value of row + column.
  • Finally, we use nested loops to iterate over the elements of the 2D array and print them in a tabular format. Each row is printed on a new line, and elements within each row are separated by spaces.

Concatenate Arrays

Concatenation of arrays in Scala refers to the process of combining two or more arrays into a single array. It involves merging the elements of multiple arrays into one array, resulting in a new array with all the elements from the original arrays.

In Scala, different approaches can be used to concatenate arrays in Scala:

  • Using the ++ Operator: The ++ operator helps to create a new array by concatenating two or more arrays.
  • Using the concat Method: The concat method is used to concatenate arrays by taking two arrays as arguments and returning a new array.
  • Using ++: for Prepending: The ++: operator is used to create a new array with the elements of the second array followed by the elements of the first array.

Example:

Let's see an example to demonstrate the concatenation of two different arrays using different approaches:

Output:

Explanation:

In this example, we create two arrays: array1 with elements [1, 2, 3] and array2 with elements [4, 5, 6].

We then demonstrate concatenation using different approaches:

  • Using the ++ operator: We concatenate array1 and array2 using ++ and assign the result to concatenatedArray1.
  • Using the concat method: We use Array.concat(array1, array2) to concatenate the arrays and assign the result to concatenatedArray2.
  • Using ++: for prepending: We prepend array2 to array1 using ++: and assign the result to concatenatedArray3.

Finally, we print the concatenated arrays using the mkString method to convert the array elements into a string representation.

Create an Array with a Range

In Scala, you can create arrays with a range of values using various methods and functions. One of the methods is the Array.range() method which creates an array with a range of values specified by the start, end, and step parameters.

Syntax:

Example:

Let us see an example that demonstrates the creation of an array in Scala with a range of values using the Array.range() method:

Output:

Explanation:

  • In this example, we create an array named array using Array.range(1, 10, 2). This creates an array with elements starting from 1 and incrementing by 2 until reaching a value of less than 10. Thus, the array will contain the values [1, 3, 5, 7, 9].
  • We then iterate over the array using a for loop and print each element to the console.

Scala Array Methods

Arrays in Scala are objects and come with several methods that allow you to manipulate and operate on array elements.

Here are some commonly used array methods in Scala:

Sr .NoMethodDescription
1apply(index: Int): TIt allows us to access the element at the specified index in the array by returning the value at the specified index.
2update(index: Int, value: T): UnitIt is used to modify the element by assigning the provided value to the element at the given index.
3length: IntIt provides the number of elements in the array by returning the size or length as an integer.
4isEmpty: BooleanThe isEmpty returns true if the array has no elements (empty) and false otherwise.
5copyToArray(dest: Array[T], destPos: Int = 0): UnitThis method copies the elements of the array to the specified destination array starting from the destPos index.
6concat(arr2: Array[T]): Array[T]The concat method concatenates the array with another array (arr2) and returns a new array containing the elements of both arrays.
7fill(length: Int)(elem: => T): Array[T]The fill method creates a new array of the specified length and fills it with elements computed from the provided expression (elem).
8 iterate(start: T, len: Int)(f: T => T): Array[T]The iterate method creates a new array by repeatedly applying a function (f) to the previous element, starting from the specified start value and up to the specified len length.
9ofDim(dim1: Int, dim2: Int, ...): Array[T]The ofDim method creates a multidimensional array with the specified dimensions.
10range(start: Int, end: Int, step: Int = 1): Array[Int]The range method creates an array of consecutive integers within the specified range, incrementing by the specified step.
11tabulate(length: Int)(f: Int => T): Array[T]The tabulate method creates a new array by applying a function (f) to each index in the specified range.
12clone: Array[T]The clone method creates a shallow copy of the array. It returns a new array that is a copy of the original array, sharing the same elements.
13 filter(p: T => Boolean): Array[T]The filter method selects and returns a new array containing only the elements that satisfy the provided predicate p.
14sortWith(comp: (T, T) => Boolean): Array[T]The sortWith method sorts the elements of the array based on the comparison function comp and returns a new array with the sorted elements.
15min: TThe min property returns the minimum element present in the array.
16 max: TThe max property returns the maximum element present in the array.

Conclusion

  • Array in Scala is a mutable, fixed-size collection that stores elements of the same type.
  • Array in Scala can be processed using various methods like iteration, mapping, filtering, and reducing, allowing you to manipulate, transform, and analyze the array elements efficiently.
  • Multidimensional array in Scala is an array of arrays, enabling the representation of data in multiple dimensions, such as a 2D grid or higher-dimensional structure.
  • Concatenation of arrays in Scala involves merging multiple arrays to create a new array with combined elements, facilitating data aggregation or extension.
  • Creating arrays with range in Scala using methods like Array.range, Array.tabulate, or Range.toArray, offering a concise way to initialize arrays with a specified range of elements.
  • Scala array methods provide operations for element access, modification, transformation, and analysis of arrays. , For example, apply, update, foreach, map, and reduce.