Search code examples
groovyoperatorsdsl

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.


Solution

  • 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