Is it possible to define a new operator in Groovy?

Is it possible to define a new operator in Groovy? I would like to express a deal when someone buys 200 items at a price of 10, like this:

def trade = 200 @ 10 

Is this achievable?

thanks

EDIT: I want to clarify that I'm interested in defining a statement that does not add a method. Greetings.

+6
source share
3 answers

I'm not quite sure how you can do this job for the @ sign, but you can certainly add an operation like this, which I actually find more expressive:

 Number.metaClass.buyFor { Integer price -> delegate * price } def result = 200.buyFor(10) println result 
+2
source

We always wanted to be able to define the operator through the user in Groovy, but so far we have not encountered problems that arise with this. Thus, the current state is that Groovy does not support user statements, only those that are already in use.

+6
source
 Number.metaClass."@" {Integer x -> delegate * x} assert (2.'@' (2)) == 4 
0
source

Source: https://habr.com/ru/post/891397/


All Articles