Local final variables do not work in Groovy
I noticed that something was really strange in Grails project I worked on. When I found out what is going on I couldn’t believe my eyes. Groovy do not respect local final variables. Yes, I really mean that, do not respect, not at all.
First of all, I want to remind how it works in java:
This code above can not be compiled. Java says:
Ok, now let’s look at the similar script in Groovy. I called it final_test.groovy, that’s it’s content:
Let’s run it:
Script was successfully compiled, no compile time errors. At runtime Groovy
ignored final
keyword and just assigned value 2 to the variable var
.
For testing I was using Java version 1.7.0_79 for MacOS and Groovy 2.4.4. The test examples are in repository. You can test it in your environment if you do not think that my experiment is good enough. :)
Maybe in the future they will fix this problem with final variables: GROOVY-1628
Be careful with that, do not rely on Groovy.
Happy coding everybody! :)