Search code examples
scalasyntaxdslsyntactic-sugar

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

  • This response is not meant to be taken too seriously - just a proof that this can almost be achieved using some hacks.

    class Vector(values: Int*) {
      val data = values.toArray
      def < (i:Int) = new {
        def `>_=`(x: Int) {
          data(i) = x
        }
        def > {
          println("value at "+ i +" is "+ data(i))
        }
      }
      override def toString = data.mkString("<", ", ", ">")
    }
    
    val v = new Vector(1, 2, 3)
    println(v) // prints <1, 2, 3>
    v<1> = 10
    println(v) // prints <1, 10, 3>
    v<1> // prints: value at 1 is 10
    

    Using this class we can have a vector that uses <> instead of () for "read" and write access. The compiler (2.9.0.1) crashes if > returns a value. It might be a bug or a result of misusing >.