Reputation: 595
Is it possible to define a brand new operator in Groovy? I would like to express a trade where someone buys 200 items for the price of 10 like this:
def trade = 200 @ 10
Is this achievable?
Thanks
EDIT: I want to make it clearer that I am interested in defining an operator not adding a method. Cheers.
Upvotes: 6
Views: 1930
Reputation: 4136
The official documentation has a section on Operator Overloading: https://groovy-lang.org/operators.html#Operator-Overloading
Upvotes: 0
Reputation: 6508
We always wanted the ability to define an operator through the user in Groovy, but so far we haven't gotten around the problems that come along with that. So the current state is that Groovy does not support custom operators, only the ones that are already in use.
Upvotes: 6
Reputation: 26
Number.metaClass."@" {Integer x -> delegate * x}
assert (2.'@' (2)) == 4
Upvotes: 0
Reputation: 33436
I am not quite sure how you can make this work for the @
sign but you could certainly add the operation like this which I actually find more expressive:
Number.metaClass.buyFor { Integer price ->
delegate * price
}
def result = 200.buyFor(10)
println result
Upvotes: 2