[
https://issues.apache.org/jira/browse/GROOVY-1628?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&focusedCommentId=17136605#comment-17136605
]
Abhiyank commented on GROOVY-1628:
----------------------------------
i think we need to re-open this ticket, the way final keyword behaves is not
right.
A final object is not Immutable you can call accessor methods on it, which is
broken now:
Consider following code:
{noformat}
class TestGroovy {
public static void main(String[] args) {
final Set<String> testSet = []
for (int i = 0; i < 4; i++) {
testSet += "asd" + i
}
println testSet
}
}
{noformat}
Which results in following output:
{noformat}
PS E:\Projects> groovy -v
Groovy Version: 3.0.4 JVM: 1.8.0_221 Vendor: Oracle Corporation OS: Windows
Server 2019
PS E:\Projects> groovy .\TestGroovy.groovy
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
E:\Projects\TestGroovy.groovy: 6: The variable [testSet] is declared final but
is reassigned
. At [6:13] @ line 6, column 13.
testSet += "asd" + i
^
1 error
{noformat}
So if the Set object is not Immutable why can't it be modified? Similar results
are observed when you try to set a final object's field.
We should be following Java's definition of final. I think this article covers
the final behaviour in detail: https://www.baeldung.com/java-final
> Inconsistent checking of final
> ------------------------------
>
> Key: GROOVY-1628
> URL: https://issues.apache.org/jira/browse/GROOVY-1628
> Project: Groovy
> Issue Type: Sub-task
> Components: Compiler
> Environment: Ubuntu 6.10 Edgy Eft + Groovy r4630
> Reporter: Dr. Russel Winder
> Assignee: Cédric Champeau
> Priority: Major
> Fix For: 2.5.0-alpha-1
>
>
> The following code appears to show that final is being applied
> inconsistently. A final list can be amended but an object that manipulates a
> lsit that is final cannot. In the former case the final is being applied to
> the reference and in the later, it is being applied to the object.
> {code}
> class Blah {
> def list = []
> public plus ( item ) {
> list += [ item ]
> return this
> }
> }
> class Foobar {
> final static blah = new Blah ( )
> }
> final x = []
> x += [1]
> println ( x )
> Foobar.blah += 1
> println ( Foobar.blah.list )
> {code}
> |> groovy finalProblem.groovy
> [1]
> Caught: java.lang.IllegalAccessException: Field is final
> at finalProblem.run(finalProblem.groovy:17)
> at finalProblem.main(finalProblem.groovy)
--
This message was sent by Atlassian Jira
(v8.3.4#803005)