jmq*_*jmq 2 groovy overloading operator-overloading
我有以下Groovy代码片段,它试图使用运算符重载来增量,减量和等于.所有这一切都是创建两个实例,执行增量并减少其中一个实例,然后使用重载方法equals比较两个实例.当我进行比较时,它失败了.当此代码完成时,两者都应为100.(打印语句显示它,但其中一个toString()函数似乎是错误的).我在这做错了什么?
这是groovy 1.8.6
class Overload {
def value
public Overload(value = 0) {
this.value = value
}
def next() {
value = value + 1;
}
def previous() {
value = value - 1;
}
def boolean equals(other) {
if (value == other?.value) {
return true
}
return false
}
def String toString() {
"value is = ${value}"
}
}
def cls1 = new Overload(100)
def cls2 = new Overload(100)
cls1++
cls1--
if (cls1 == cls2) {
println("cls1 == cls2")
}
else {
println("cls1 != cls2")
}
println(cls1.toString())
println(cls2.toString())
Run Code Online (Sandbox Code Playgroud)
输出:
cls1 != cls2
100
value is = 100
Run Code Online (Sandbox Code Playgroud)
问题是Overload实例的增量和减量方法.
Groovy具有对最后一个表达式求值的隐式返回的特性.当你调用时cls1++,现在对象是一个Integer,这就是我们没有看到覆盖toString方法输出的原因.
def next() {
value = value + 1
return this
}
def previous() {
value = value - 1
return this
}
Run Code Online (Sandbox Code Playgroud)
现在检查:
assert cls1.class == Overload
assert cls2.class == Overload
assert cls1 == cls2
assert cls1 == 100
assert cls2 == 100
Run Code Online (Sandbox Code Playgroud)