14

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.

1
  • 1
    You mean angle bracket in method calls, not in method names? Commented Jul 4, 2011 at 13:20

3 Answers 3

41

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 >.

Sign up to request clarification or add additional context in comments.

4 Comments

Very nice. I had tried to define >_= but didn't try with the backticks. Cool!
If the compiler actually crashes (prints a stack trace and exits), it's a bug. Please report it if that's the case.
@Aaron Novstrup: I just filed a bug for the issue.
>_= so looks like a moe face, by the way.
6

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 

Comments

1

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...

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.