How can I implement a Class which can ask just like Array, providing indexed setter?
like:
val k = new MyKls(size)
k(0) = 2 //<<-- I want this kind of functionality.
Thanks.
It sounds like what you are looking for is the update
method. If you define this method, then Scala will use it in the k(0) = 2
syntax. It is similar to the apply
method which allows you do use the k(0)
accessor syntax.
Here's a short example:
import scala.collection.mutable.Buffer
class MyKls(size: Int) {
val buf = Buffer.fill(size)(0)
def apply(index: Int) = buf(index)
def update(index: Int, newValue: Int) { buf(index) = newValue }
override def toString = buf.mkString("[", ", ", "]")
}
val k = new MyKls(5)
println(k) // [0, 0, 0, 0, 0]
k(0) = 2
println(k) // [2, 0, 0, 0, 0]
println(k(0)) // 2
You can find some more detail here.