
- Scala - Home
- Scala - Overview
- Scala - Features
- Scala - Environment Setup
- Scala - Build Tool (SBT)
- Scala - REPL
- Scala - Dot & Dotty
- Scala - Basic Syntax
- Scala - Hello World Program
- Scala - Identifiers
- Scala - Keywords
- Scala - Comments
- Scala - Code Blocks
- Scala - Semicolon
- Scala - Constructs
- Scala - Expressions
- Scala - Input and Output
- Scala - Optional Braces
- Scala - Underscore (_)
- Data Types and Variables
- Scala - Data Types
- Scala - Type Bounds
- Scala - Context Bound
- Scala - Variances
- Scala - Type Hierarchy
- Scala - Variables
- Scala - Variable Scopes
- Scala - Literals
- Scala - Numeric Types
- Scala - Boolean Types
- Scala - Char Type
- Scala - Unit Types
- Scala - Strings
- Scala - Arrays
- Scala - Null Type
- Scala - Nothing
- Scala - Any Type
- Scala - AnyRef Type
- Scala - Unified Types
- Scala - Dates and Times
- Scala - Ranges
- Scala - Multidimensional Arrays
- Scala - WrappedArray
- Scala - StringBuilder
- Scala - String Interpolation
- Scala - StringContext
- Scala - Type Casting
- Scala var vs val
- Scala Operators
- Scala - Operators
- Scala - Rules for Operators
- Scala - Arithmetic Operators
- Scala - Relational Operators
- Scala - Logical Operators
- Scala - Bitwise Operators
- Scala - Assignment Operators
- Scala - Operators Precedence
- Scala - Symbolic Operators
- Scala - Range Operator
- Scala - String Concatenation Operator
- Scala Conditional Statements
- Scala - IF ELSE
- Scala - IF-ELSE-IF-ELSE Statement
- Scala - Nested IF-ELSE Statement
- Scala Loop Statements
- Scala - Loop Statements
- Scala - while Loop
- Scala - do-while Loop
- Scala - Nested Loops
- Scala - for Loop
- Scala - break Statement
- Scala - yield Keyword
- Scala Classes & Objects
- Scala - Classes & Objects
- Scala - Constructors
- Scala - Auxiliary Constructor
- Scala - Primary Constructor
- Scala - This Keyword
- Scala - Nested Classes
- Scala - Getters and Setters
- Scala - Object Private Fields
- Scala - Singleton Object
- Scala - Companion Objects
- Scala - Creating Executable Programs
- Scala - Stateful Object
- Scala - Enumerations
- Scala - Polymorphism
- Scala - Access Modifiers
- Scala - Apply Method
- Scala - Update Methods
- Scala - UnapplySeq Method
- Scala - Inheritance
- Scala - Extending a Class
- Scala - Method Overloading
- Scala - Method Overriding
- Scala - Generic Classes
- Scala - Generic Functions
- Scala - Superclass Construction
- Scala Methods & Functions
- Scala - Functions
- Scala - Main Methods
- Scala - Functions Call-by-Name
- Scala - Functions with Named Arguments
- Scala - Function with Variable Arguments
- Scala - Recursion Functions
- Scala - Default Parameter Values
- Scala - Functions without Parameters
- Scala - Implicit Parameters
- Scala - Higher-Order Functions
- Scala - Nested Functions
- Scala - Extension Methods
- Scala - Anonymous Functions
- Partially Applied Functions
- Scala - Lazy Val
- Scala - Pure Function
- Scala - Currying Functions
- Scala - Control Abstractions
- Scala - Corecursion
- Scala - Unfold
- Scala - Tail Recursion
- Scala - Infinite Sequences
- Scala - Dynamic Invocation
- Scala - Lambda Expressions
- Scala Collections
- Scala - Collections
- Mutable and Immutable Collections
- Scala - Lists
- Scala - Sets
- Scala - Maps
- Scala - TreeMap
- Scala - SortedMap
- Scala - Tuples
- Scala - Iterators
- Scala - Options
- Scala - Infinite Streams
- Scala - Parallel Collections
- Scala - Algebraic Data Types
- Scala Pattern Matching
- Scala - Pattern Matching
- Scala - Type Patterns
- Scala - Exception Handling
- Scala - Extractors
- Scala - Regular Expressions
- Scala Files I/O
- Scala - Files I/O
- Scala Advanced Concepts
- Scala - Closures
- Scala - Futures
- Scala - Promises
- Scala - Traits
- Scala - Trait Mixins
- Scala - Layered Traits
- Scala - Trait Linearization
- Scala - Sealed Traits
- Scala - Transparent Traits
- Scala - Literal Type Arithmetic
- Scala - Inline keyword
- Scala - Def, Var & Val
- Scala - Dropped Features
- Scala - BDD Testing
Scala - Multidimensional Arrays
There are many situations where you would need to define and use multi-dimensional arrays (i.e., arrays whose elements are arrays). For example, matrices and tables are examples of structures that can be realized as two-dimensional arrays.
The following is the example of defining a two-dimensional array −
var myMatrix = ofDim[Int](3,3)
This is an array that has three elements each being an array of integers that has three elements.
Example of Multidimensional Arrays
Try the following example program to process a multi-dimensional array −
import Array._ object Demo { def main(args: Array[String]) { var myMatrix = ofDim[Int](3,3) // build a matrix for (i <- 0 to 2) { for ( j <- 0 to 2) { myMatrix(i)(j) = j; } } // Print two dimensional array for (i <- 0 to 2) { for ( j <- 0 to 2) { print(" " + myMatrix(i)(j)); } println(); } } }
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
Command
\>scalac Demo.scala \>scala Demo
Output
0 1 2 0 1 2 0 1 2
Another Way to Create Multi-Dimensional Array
In Scala, the usual method to create an array and work with its elements is by using the apply and update methods. For example, you can define a One-dimensional array, like this:
val intArray: Array[Int] = Array(7, 14, 21) println(intArray(1)) intArray(1) = 28 println(intArray(1))
Multidimensional Array Using Array.ofDim(), Array.fill(), and Array.tabulate()
A multi-dimensional array is an array of arrays. In Scala, you can create multi-dimensional arrays using methods like Array.ofDim(), Array.fill(), and Array.tabulate().
- ofDim() creates an array with the specified dimensions but does not initialize its elements.
- fill() creates an array and initializes all elements with a given value.
- tabulate() generates an array where each element is computed based on its indices.
// Creating a 2D array with 2 rows and 3 columns // (elements initialized to 0 by default) val matrix = Array.ofDim[Int](2, 3) // Creating a 3D array (2x3x4), // initializing all elements to 1 val cubeFill = Array.fill(2, 3, 4)(1) // Creating a 3D array (2x3x5) // where each element is computed using the indices val cubeTabulate = Array.tabulate(2, 3, 5) { case (x, y, z) => x * y * z }
Here,
- The first array, matrix, is a 2D array with 2 rows and 3 columns, where each element is initialized to 0 (the default value for Int).
- The second array, cubeFill, is a 3D array with 2 layers, 3 rows, and 4 columns, where each element is initialized to 1. The last argument of Array.fill specifies the default value.
- The third array, cubeTabulate, is also a 3D array but initialized dynamically using a function. Each element is calculated based on its indices using x * y * z.
Multidimensional Array by Using Array of Array
You can create multidimensional array by using an array of arrays. For example, Scala Program of Multidimensional array using Array of Array.
Example
Try the following example program −
object Demo { def main(args: Array[String]): Unit = { // Creating and assigning values to the array var customArr = Array(Array(10, 20, 30, 40, 50), Array(15, 25, 35, 45, 55)) for (rowIndex <- 0 to 1) { for (colIndex <- 0 to 4) { // Accessing the values print(" " + customArr(rowIndex)(colIndex)) } println() } } }
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
Command
\>scalac Demo.scala \>scala Demo
Output
10 20 30 40 50 15 25 35 45 55
Example
Another example for printing elements with row and column. Scala Program of Multidimensional array using Array of Array −
object Demo { def main(args: Array[String]): Unit = { // Creating and assigning values to the array var customArray = Array(Array(10, 20, 30, 40, 50), Array(15, 25, 35, 45, 55)) for (rowIndex <- 0 to 1; colIndex <- 0 until 5) { print(s"$rowIndex, $colIndex") // Accessing the elements println(s" = ${customArray(rowIndex)(colIndex)}") } } }
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
Command
\>scalac Demo.scala \>scala Demo
Output
0, 0 = 10 0, 1 = 20 0, 2 = 30 0, 3 = 40 0, 4 = 50 1, 0 = 15 1, 1 = 25 1, 2 = 35 1, 3 = 45 1, 4 = 55
Printing Multidimensional Arrays
It is a tough task to print multi-dimensional arrays. It depends on the number of dimensions in the given array.
For example, this is function to print a multidimensional array:
def printMultidimensionalArray[T](array: Array[Array[T]]): Unit = array.foreach(row => println(row.mkString(" "))) // Example usage: printMultidimensionalArray(matrixFill) println("--") printMultidimensionalArray(matrixTabulate)
This will work based on the array dimension. Above code will take two-dimensional array. It will iterate over each element of the array and convert elements of arrays into strings separated by spaces. Then it will print each string on newlines. Since this function is generic, it can work with two different two-dimensional arrays, i.e., matrixFill and matrixTabulate.
Suppose these arrays are as:
val matrixFill: Array[Array[Int]] = Array( Array(1, 2, 3), Array(4, 5, 6), Array(7, 8, 9) ) val matrixTabulate: Array[Array[Int]] = Array( Array(10, 20, 30), Array(40, 50, 60), Array(70, 80, 90) )
So, output of the code will be,
1 2 3 4 5 6 7 8 9 -- 10 20 30 40 50 60 70 80 90
Multi-dimensional arrays store elements in matrix format. You need multidimensional arrays for matrices and tables.