'method with angle brackets (<>)

Is it possible to have angle brackets in method names , e.g. :

class Foo(ind1:Int,ind2:Int){...}
var v = new Foo(1,2)
v(1) = 3 //updates ind1
v<1> = 4 //updates ind2

The real situation is obviously more complicated than this!!I am trying to provide a convenient user interface.



Solution 1:[1]

Edit: I was wrong; kassens's answer shows how to do it as you want.


It is not possible to implement a method that would be called when you write v<1> = 4 (except, maybe, if you write a compiler plugin?). However, something like this would be possible:

class Foo {
  def at(i: Int) = new Assigner(i)
  class Assigner(i: Int) {
    def :=(v: Int) = println("assigning " + v + " at index " + i)
  }
}

Then:

val f = new Foo
f at 4 := 6

Solution 2:[2]

With a little trickery you can actually get quite close to what you want.

object Foo {
  val a:Array[Int] = new Array(100)
  def <(i:Int) = new Updater(a, i)
}

class Updater(a:Array[Int], i:Int) {
  def update(x:Int) {
    a(i) = x
  }
  def >() = this
}

Foo<1>() = 123

I am not sure why Scala requires the () though. And yes, this is a bit of a hack...

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2