Is it possible to define a new operator in Groovy?
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.
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.
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
Number.metaClass."@" {Integer x -> delegate * x}
assert (2.'@' (2)) == 4
The official documentation has a section on Operator Overloading: https://groovy-lang.org/operators.html#Operator-Overloading
Here is a list from the docs:
精彩评论