Setting instance vars with apply

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!
}

Answers


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

Need Your Help

Sharding & Replication in mongodb

mongodb database-replication sharding replicaset

First of all, I'm a beginner in mongoDB so please be patient with me. I'm using windows and I created a simple database that contains 4 collections. When I'm dealing with mongoDB, I first run: mong...

position div under min-height div

css

My question here is - how to position div to stick at the bottom of another div that has min-height style atribute.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.