是否可以在 Groovy 中定义一个新的运算符?

发布于 2024-11-17 00:45:20 字数 179 浏览 4 评论 0原文

是否可以在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

┈┾☆殇 2024-11-24 00:45:20

我们一直希望能够在 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.

ぶ宁プ宁ぶ 2024-11-24 00:45:20

我不太确定如何使 @ 符号发挥作用,但您当然可以添加这样的操作,我实际上发现它更具表现力:

Number.metaClass.buyFor { Integer price ->
   delegate * price
}

def result = 200.buyFor(10)
println result

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
浮世清欢 2024-11-24 00:45:20
Number.metaClass."@" {Integer x -> delegate * x} 

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

assert (2.'@' (2)) == 4
束缚m 2024-11-24 00:45:20

官方文档有一节关于运算符重载: 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: List of overloadable operators

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文