是否可以在 Groovy 中定义一个新的运算符?
是否可以在 Groovy 中定义一个全新的运算符?我想表达这样的交易:某人以 10 件的价格购买 200 件物品:
def trade = 200 @ 10
这可以实现吗?
谢谢
编辑:我想更清楚地表明我对定义运算符而不是添加方法感兴趣。干杯。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我们一直希望能够在 Groovy 中通过用户定义运算符,但到目前为止我们还没有解决随之而来的问题。所以目前的状态是 Groovy 不支持自定义运算符,仅支持已经在使用的运算符。
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:官方文档有一节关于运算符重载: https://groovy-lang.org/ Operators.html#Operator-Overloading
以下是文档中的列表:
The official documentation has a section on Operator Overloading: https://groovy-lang.org/operators.html#Operator-Overloading
Here is a list from the docs: