使用apply设置实例变量

时间:2013-05-02 02:44:06

标签: scala

使用Array,可以使用val i = xs(0)xs(0) = i语法来获取和设置元素。如何在我自己的类中实现此功能?到目前为止,我只能实现获取值。

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

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

更新:感谢Mauricio对update方法的回答。这是最终版本

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 个答案:

答案 0 :(得分:2)

您需要声明update方法:

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