3

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.

wliao
  • 1,416
  • 11
  • 18

1 Answers1

8

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.

dhg
  • 52,383
  • 8
  • 123
  • 144
  • 1
    This question may also be useful in understanding the other special methods: http://stackoverflow.com/q/1483212/547212 – mpilquist Sep 13 '12 at 03:55