Overload Index Operator in Scala

Tag: scala Author: qibude Date: 2011-11-07

Is it possible to overload the index operator in Scala?
If yes, what would the scala version of this c++ example look like?

class Foo {
  int data[7];
  int& operator[](size_t i) { return data[i]; }
  int  operator[](size_t i) const { return data[i]; }

Best Answer

The index operator in scala is (), and you can define a method which looks like it. You need to define an apply method.

scala> class Foo(v: String) { def apply(i: Int) = v(i) }
defined class Foo

scala> val f = new Foo("foobar")
f: Foo = [email protected]

scala> f(3)
res3: Char = b

Other Answer1

No, it is not possible to overload the index operator, [ and ] are reserved by the language for specifying type information (List[String] for example) and so are unavailable for that use. What you can use is the apply function. The closest equivalent to what you have in your c++ example would be:

class Foo {
    val data = Array.ofDim[Int](7)
    def apply(i : Int) : Int = data(i)

//Usage :
//var f = new Foo
//val aNumber = f(0) 
//aNumber == f.data(0)

The apply function in scala is simply some syntactic sugar, if you have it defined then f(0) gets expanded to f.apply(0) behind the scenes. If you want to be able to use statements like f(0) = 4 you can do that as well, by means of the related update function.