【问题标题】:Why `++` increments final field in Groovy?为什么 `++` 在 Groovy 中增加 final 字段?
【发布时间】:2021-06-06 22:41:34
【问题描述】:

今天,我在 Groovy 中遇到了相当奇特的问题/功能。 看起来可以在 Groovy 中使用 ++ 运算符增加最终字段。

在您看来,它看起来像一个错误吗?这种行为与我对 Java 的期望不一致。 有谁知道这怎么可能?

我已经准备了一个小的 Spock 测试来查明问题。

import spock.lang.Specification


class FinalModifierTest extends Specification {

    def 'tests bizarre behaviour of final modifier in Groovy'() {
        given:
            Adder adder = new Adder()

            expect:
            adder.number.class == Integer

            when:
            adder.number = 7

            then:
            thrown(ReadOnlyPropertyException)

            when:
            adder.increment()

            then:
            adder.number == 2
        }
    }

    class Adder {
        final int number = 1

        void increment() {
            number++
        }
}

显然,InteliJ 通过显示以下消息通知我有关最终字段分配的信息: '无法为最终字段编号赋值',但代码仍然可以编译,更糟糕的是,它执行成功!

我在上面的例子中运行:

JVM:1.7.0_51

Groovy:2.2.2

【问题讨论】:

    标签: groovy


    【解决方案1】:

    你觉得它是个 bug 吗?

    是的。如果您愿意,可以通过 https://issues.apache.org/jira/projects/GROOVY 提交 JIRA,我们可以查看。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-02
    • 2011-02-16
    • 1970-01-01
    • 2014-05-23
    • 2019-11-02
    相关资源
    最近更新 更多