What is ofDim in Scala?

Scala allows us to declare multi-dimensional arrays via the ofDim function. The function does so by using a matrix format.

We can declare multidimensional arrays using Array.ofDim.

Syntax

Array Array.ofDim[data_type](num_rows, num_cols)

Parameters

The ofDim function takes two parameters, which are related to the dimensions of the array matrix that will be created. The datatype of the array content also needs to be specified while declaring the array.

  1. num_rows: the number of rows in the array
  2. num_cols: the number of columns in the array

Return value

The function returns a multidimensional array.

A 2D array in a matrix format

Code

The following code shows how we can use the ofDim function to make multidimensional arrays in Scala.

object Main extends App{
//Using ofDim function to create an array of 3 rows and 4 columns
val mymultiarr= Array.ofDim[Int](3, 4)
//Assigning values to all indices in the 2d array
mymultiarr(0)(0) = 1
mymultiarr(0)(1) = 2
mymultiarr(0)(2) = 3
mymultiarr(0)(3) = 4
mymultiarr(1)(0) = 5
mymultiarr(1)(1) = 6
mymultiarr(1)(2) = 7
mymultiarr(1)(3) = 8
mymultiarr(2)(0) = 9
mymultiarr(2)(1) = 10
mymultiarr(2)(2) = 11
mymultiarr(2)(3) = 12
for(i<-0 to 2) //indexing the array
{
for(j<-0 to 3){
print(mymultiarr(i)(j))
print(" ")
}
println()
}
}

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved