How to create and use multi-dimensional arrays (2D, 3D, etc.) in Scala

Here's a quick look at how to create a multi-dimensional array in Scala, in this case a 2D array (matrix), and then access the array elements. As you can see, these commands were issued using the Scala REPL, and I've added a few comments to them:

// create a 2D array
scala> val matrix = Array.ofDim[Int](2,2)
matrix: Array[Array[Int]] = Array(Array(0, 0), Array(0, 0))

// populate the array elements
scala> matrix(0)(0) = 0

scala> matrix(0)(1) = 1

scala> matrix(1)(0) = 2

scala> matrix(1)(1) = 3

// access a couple of array elements
scala> matrix(0)(1)
res4: Int = 1

scala> matrix(1)(0)
res5: Int = 2

If you ever need to create a multidimensional array in Scala, I hope this example is helpful.

This website is a little one-man operation. If you found this information helpful, I’d appreciate it if you would share it.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image.