1

With Array it's possible to get and set elements with val i = xs(0) and xs(0) = i syntax. How to implement this functionality in my own class? So far I was only able to implement getting the values.

class Matrix(val m : Int, val n : Int) {
  val matrix = Array.ofDim[Double](m, n)

  def apply(i:Int)(j:Int) = matrix(i)(j)
}

UPDATE: Thanks to Mauricio for answer about update method. That's the final version

class Matrix(val m:Int, val n:Int) {
  private val matrix = Array.ofDim[Double](m, n)
  def apply(i:Int) = new {
    def apply(j:Int) = matrix(i)(j)

    def update(j:Int, v:Double) = { matrix(i)(j) = v }
  }
}

it("matrix") {
  val m = new Matrix(3, 3)
  m(0)(1) = 10.0
  val x = m(0)(1)

  x should equal(10.0)
  x.isNegInfinity should be (false) // Implicits for Double work!
}

1 Answer 1

2

You need to declare an update method:

class Matrix(val m : Int, val n : Int) {
  private val matrix = Array.ofDim[Double](m, n)

  def apply(i:Int)(j:Int) = matrix(i)(j)

  def update( i : Int, j : Int, value : Double) {
    matrix(i)(j) = value
  }

}

val m = new Matrix( 10, 10 )
m(9, 9) = 50
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. So if I want to use exactly the same syntax as multidim array, I need to implement MatrixRow class with update and apply methods and return it from Matrix's apply. Is there a way to create some anonymous class instead instead of explicit class definition?
A caller won't know what methods an anonymous class implements unless you make it a trait and return this trait implemented by the returned anonymous object.
It looks like it typechecks even without a trait. I've updated the question with the code that works.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.