简体   繁体   中英

Why `++` increments final field in Groovy?

Today, I came across rather peculiar issue/feature in Groovy. It looks like it is possible to increment a final field using ++ operator in Groovy.

Does it look like a bug to you? This behaviour is not consistent with what I would expect from Java. Does anyone have any idea how is it possible?

I have prepared a little Spock test to pin point the problem.

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!

I was running above example on:

JVM: 1.7.0_51

Groovy: 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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