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.
Usage of angle bracketsIn some languages, a double set of angle brackets may be used in place of quotation marks to contain quotes. In English, they may be used informally to insert asides, indicate speech in a foreign language, or to mention a website, but all of these uses are rare even in informal writing.
Angle Bracket in Java is used to define Generics. It means that the angle bracket takes a generic type, say T, in the definition and any class as a parameter during the calling. The idea is to allow type (Integer, String, … etc and user-defined types) to be a parameter to methods, classes, and interfaces.
Angle brackets are commonly used to enclose a code of some type. For example, HTML tags and PageMaker tags are enclosed in angle brackets.
One within the parentheses () and another within the angle brackets < > We know in the function call func(12) , argument 12 within the parentheses represents the arg parameter. Similarly in func<number>(12) , the argument number within the angle brackets represents the generic type parameter T .
This response is not meant too serious and is 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 >
.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With