有没有可能在Groovy中定义一个新的操作符? [英] Is it possible to define a new operator in Groovy?

查看:110
本文介绍了有没有可能在Groovy中定义一个新的操作符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在Groovy中定义一个全新的运算符?我想表达一个交易,其中有人购买了200件物品,价格为10美元,如下所示:

  def trade = 200 @ 10 

是否可以实现?

/ p>

编辑:我想更清楚一点,我有兴趣定义一个不添加方法的运算符。干杯。

解决方案

我不太清楚您如何为 @ sign,但是你当然可以添加这样的操作,我实际上可以发现更多的表达:

  Number.metaClass.buyFor {整数价格 - > 
委托*价格
}

def结果= 200.buyFor(10)
println结果


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.

解决方案

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

这篇关于有没有可能在Groovy中定义一个新的操作符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆