11.11. Creating Multidimensional Arrays

Problem

You need to create a multidimensional array, i.e., an array with two or more dimensions.

Solution

There are two main solutions:

  • Use Array.ofDim to create a multidimensional array. You can use this approach to create arrays of up to five dimensions. With this approach you need to know the number of rows and columns at creation time.

  • Create arrays of arrays as needed.

Both approaches are shown in this solution.

Using Array.ofDim

Use the Array.ofDim method to create the array you need:

scala> val rows = 2
rows: Int = 2

scala> val cols = 3
cols: Int = 3

scala> val a = Array.ofDim[String](rows, cols)
a: Array[Array[String]] = Array(Array(null, null, null), Array(null, null, null))

After declaring the array, add elements to it:

a(0)(0) = "a"
a(0)(1) = "b"
a(0)(2) = "c"
a(1)(0) = "d"
a(1)(1) = "e"
a(1)(2) = "f"

Access the elements using parentheses, similar to a one-dimensional array:

scala> val x = a(0)(0)
x: String = a

Iterate over the array with a for loop:

scala> for {
     |   i <- 0 until rows
     |   j <- 0 until cols
     | } println(s"($i)($j) = ${a(i)(j)}")
(0)(0) = a
(0)(1) = b
(0)(2) = c
(1)(0) = d
(1)(1) = e
(1)(2) = f

To create an array with more dimensions, just follow that same pattern. Here’s the code for a three-dimensional array:

val x, y, z = 10
val a = Array.ofDim[Int](x,y,z)
for {
  i <- 0 until x
  j <- 0 until y
  k <- 0 until z
} println(s"($i)($j)($k) = ${a(i)(j)(k)}")

Using an array of arrays

Another approach is to create an array whose elements are arrays: ...

Get Scala Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.