Search code examples
arraysscalacompiler-errorsmutable

Creating a Matrix - "Value update is not a member of Example.Matrix" error


I am trying to create a simple matrix (basically porting some code I wrote in C++ to understand Scala better). The code I wrote is:

object Example extends App {
  case class Matrix(rows: Int = 1, columns: Int = 1) {
    val data = Array.fill[Int](rows * columns)(0)
    def apply(i: Int, j: Int) = this.data(i * columns + j)
  }

  val grid = Matrix()

  grid(0, 0) = 10
}

This does not compile, but from what I can tell this is equivalent to my working C++ example logically. Clearly something weird is going on due to the apply function.

Can someone please explain why this code is not compiling? I cant seem to figure it out.

Any guidance is much appreciated!


Solution

  • val foo = gir(0, 0) will call apply, but grid(0, 0) = foo will call update.

    You need to define it like this:

    def update(i: Int, j: Int, x: Int): Unit = {
      this.data(i * columns + j) = x
    }
    

    BTW, a case class must not be mutable! So, please use a normal class.
    And, it may be good to make data private.


    Anyways, mutability in general as well as Arrays are not common in Scala. IMHO, the best way to understand Scala better is not try to port imperative code, but rather rethink functional solutions to the same problems.