简体   繁体   English

为什么`++` 在Groovy 中增加final 字段?

[英]Why `++` increments final field in Groovy?

Today, I came across rather peculiar issue/feature in Groovy.今天,我在 Groovy 中遇到了相当奇怪的问题/功能。 It looks like it is possible to increment a final field using ++ operator in Groovy.看起来可以在 Groovy 中使用++运算符来增加 final 字段。

Does it look like a bug to you?对你来说它看起来像一个错误吗? This behaviour is not consistent with what I would expect from Java.这种行为与我对 Java 的期望不一致。 Does anyone have any idea how is it possible?有谁知道这怎么可能?

I have prepared a little Spock test to pin point the problem.我准备了一个小的 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++
        }
}

Obviously, InteliJ informed me about final field assignment by showing below message: 'Cannot assign a value to a final field number', however the code still compiles and what is worse, it executes successfully!显然,InteliJ 通过显示以下消息告诉我有关最终字段分配的信息:“无法为最终字段编号分配值”,但是代码仍然可以编译,更糟糕的是,它成功执行了!

I was running above example on:我在上面的例子上运行:

JVM: 1.7.0_51 JVM:1.7.0_51

Groovy: 2.2.2常规:2.2.2

Does it look like a bug to you?对你来说它看起来像一个错误吗?

Yes.是的。 If you like you can file a JIRA at https://issues.apache.org/jira/projects/GROOVY and we can take a look.如果您愿意,可以在https://issues.apache.org/jira/projects/GROOVY提交 JIRA,我们可以查看。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM