使用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!
}
答案 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