1

可以使用和语法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!
}
4

1 回答 1

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
于 2013-05-02T02:59:18.460 回答