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
valonly makes the variable cannot be reassigned by other collection but you still can reassign the field in the collectionArrayis mutable (even if the reference to it is not). You can simply useIndexedSeqwhich serves as a generic trait for sequences with constant random access. The official documentation has a very interesting chapter on collections and their characteristics: docs.scala-lang.org/overviews/collections/overview.html