Groovy 中的基本运算符重载
elementary operator overloading in Groovy
我是 Groovy 的新手,之前只用过 C# 和 C++,所以我在习惯 Java 尤其是 Groovy 方面遇到了一些问题我们的项目。所以问题涉及 Groovy.
我正在尝试:
- 创建一个新的 class X:
class X {
double val
}
- 为 class X
的变量重载基本运算符(+、-、*、/、** 等)
问题是:
- 在 Groovy 中,我可以重载 class X 的运算符,包括一个属性 - 值(即双精度值)
X plus(X obj){
X newobj = new X(this.val + obj.val)
return newobj
}
和
X plus(double obj){
X newobj = new X(this.val + obj)
return newobj
}
但是双对象又在第一位(左手边)怎么办?喜欢:
double a
X b
X result = a + b
// it will not work because operator + of a is not overloaded to provide addition of b
除了双重运算符,我是否需要重载这样的东西?:
ArrayList.metaClass.plus << {Collection b ->
[delegate, b].transpose().collect{x, y -> x+y}
}
正如在
Overloading + operator for arrays in groovy
也许有办法添加一个方法作为闭包访问元数据class?
不幸的是,数组示例是我在互联网上找到的最接近的答案。希望有办法!
是的,您可以为 Double 重新定义它:Double.metaClass.plus = {...}
小心!在 groovy
def d0 = 2.1
println d0.getClass() // java.math.BigDecimal
double d1 = 2.1
println d1.getClass() // java.lang.Double
我是 Groovy 的新手,之前只用过 C# 和 C++,所以我在习惯 Java 尤其是 Groovy 方面遇到了一些问题我们的项目。所以问题涉及 Groovy.
我正在尝试:
- 创建一个新的 class X:
class X {
double val
}
- 为 class X 的变量重载基本运算符(+、-、*、/、** 等)
问题是: - 在 Groovy 中,我可以重载 class X 的运算符,包括一个属性 - 值(即双精度值)
X plus(X obj){
X newobj = new X(this.val + obj.val)
return newobj
}
和
X plus(double obj){
X newobj = new X(this.val + obj)
return newobj
}
但是双对象又在第一位(左手边)怎么办?喜欢:
double a
X b
X result = a + b
// it will not work because operator + of a is not overloaded to provide addition of b
除了双重运算符,我是否需要重载这样的东西?:
ArrayList.metaClass.plus << {Collection b ->
[delegate, b].transpose().collect{x, y -> x+y}
}
正如在 Overloading + operator for arrays in groovy
也许有办法添加一个方法作为闭包访问元数据class?
不幸的是,数组示例是我在互联网上找到的最接近的答案。希望有办法!
是的,您可以为 Double 重新定义它:Double.metaClass.plus = {...}
小心!在 groovy
def d0 = 2.1
println d0.getClass() // java.math.BigDecimal
double d1 = 2.1
println d1.getClass() // java.lang.Double