2

我有以下 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())

输出:

cls1 != cls2
100
value is = 100
4

2 回答 2

6

问题是Overload实例的增量和减量方法。

Groovy 具有隐式返回最后评估的表达式的特性。当您调用 to 时cls1++,现在对象是一个整数,这就是我们看不到被覆盖toString方法的输出的原因。

def next() {
    value = value + 1
    return this
}

def previous() {
    value = value - 1
    return this
}

现在检查:

assert cls1.class == Overload
assert cls2.class == Overload
assert cls1 == cls2
assert cls1 == 100
assert cls2 == 100
于 2012-05-15T23:06:44.550 回答
1

作为一个快速的附加评论,您不需要def在定义方法的返回类型时使用。您的课程更简洁的版本是:

class Overload {
    def value

    public Overload(value = 0) {
        this.value = value
    }

    def next() {
        value = value + 1
        this
    }

    def previous() {
        value = value - 1
        this
    }

    boolean equals(other) {
        value == other?.value
    }

    String toString() {
        "value is = ${value}"
    }
}
于 2012-05-16T08:47:02.190 回答