Abir Chokraborty
Abir Chokraborty

Reputation: 1765

How to make immutable 2D Array in Scala

I have the following class:

class Matrix(val matrix: Array[Array[Int]]) {
// some other methods
override def toString: String = {
    return matrix.map(_.mkString(" ")).mkString("\n")
  }   
}

I have declared class variable as val to prevent further modification in matrix.

object Main {
  def main(args: Array[String]) {

    val > = Array
    val x: Array[Array[Int]] = >(
      >(1, 2, 3),
      >(4, 5, 6),
      >(7, 8, 9))

    val m1 = new Matrix(x)
    println("m1 -->\n" + m1)
    x(1)(1) = 101 // Need to prevent this type of modification.
    println("m1 -->\n" + m1)
  }
}

After doing x(1)(1) = 101 the output of the program is

m1 -->
1 2 3
4 101 6
7 8 9

But I want to prevent this modification and get the original matrix as

m1 -->
1 2 3
4 5 6
7 8 9

Upvotes: 2

Views: 649

Answers (2)

Tony Ng Wei Shyang
Tony Ng Wei Shyang

Reputation: 485

Instead of using Array, maybe you could use List instead, and it is immutable :

scala> val num:List[Int] = List(1,2,3)
num: List[Int] = List(1, 2, 3)

scala> num(1) = 3
<console>:13: error: value update is not a member of List[Int]
   num(1) = 3
   ^

Upvotes: 1

jwvh
jwvh

Reputation: 51271

There's a difference between a mutable/immutable variable (e.g. var x and val x) and a mutable/immutable collection. Declaring one (the variable) doesn't effect the other (the collection).

The Scala Array is inherited from Java and, as such, is mutable. There are many fine immutable collections. Array isn't one of them.

Upvotes: 0

Related Questions