Is it possible to define a new operator in Groovy?

走远了吗. 提交于 2020-01-03 12:30:08

问题


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.


回答1:


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



回答2:


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.




回答3:


Number.metaClass."@" {Integer x -> delegate * x} 

assert (2.'@' (2)) == 4


来源:https://stackoverflow.com/questions/6485861/is-it-possible-to-define-a-new-operator-in-groovy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!