Why does `++` grow a finite field in Groovy?

I ran into a rather peculiar problem / feature in Groovy today. It looks like it is possible to increase the target field using an operator ++

in Groovy.

Does this look like a bug? This behavior is inconsistent with what I expect from Java. Does anyone know how this is possible?

I prepared a small Spock test to indicate 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++
        }
}

      

Apparently InteliJ informed me of the final field assignment by displaying the message below: "Cannot assign value to final field number", however the code still compiles, and worse, it succeeds!

I was working on an example:

JVM: 1.7.0_51

Groovy: 2.2.2

+3


source to share


1 answer


Does this look like a bug?



Yes. If you like, you can submit JIRA at https://jira.codehaus.org/browse/GROOVY and we can take a look.

+4


source







All Articles