Reputation: 240
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];
...
public:
int& operator[](size_t i) { return data[i]; }
int operator[](size_t i) const { return data[i]; }
...
};
Upvotes: 3
Views: 2237
Reputation: 61705
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 = Foo@c3dd7e
scala> f(3)
res3: Char = b
Upvotes: 8
Reputation: 2852
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.
Upvotes: 10