Final Variables in Groovy Curiosity
(On my local I’m running Groovy 2.1.9 on Java/JDK 6).
Was having a Discussion of final and static, and decided to try something in groovyConsole. In the Java world, a final variable cannot be reassigned a value once initialized.
Groovy Code:
final String i = “test”
println i
i = “red”
println i
Output:
groovy> final String i = “test”
groovy> println i
groovy> i = “red”
groovy> println i
test
red
Interesting — Groovy completely ignored final. If I plug the code into a Java compiler I get a compilation error — can’t reassign.
I sent this off to a buddy of mine who teaches Groovy to corporate and he found it odd, and said this behavior happens for this example as well:
Groovy Code:
def junk() {
final int a = 42;
a = 99;
}
println junk()
Output:
groovy> def junk() {
groovy> final int a = 42;
groovy> a = 99;
groovy> }
groovy> print junk()
99
The discussion is a little extended, found this though — the issue for final is still open as of this date (March 12, 2014):
http://jira.codehaus.org/browse/GROOVY-4681