Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'final' keyword in Groovy

Tags:

groovy

Is this a bug or a deliberate design decision by the folks at Groovy?

final String x = "a"
x = "b"

You run this and it would work, no problem. Shouldn't a runtime exception be thrown instead? Annotating the class with @CompileStatic didn't help either. I was expecting a compilation error when @CompileStatic is used.

like image 714
Ankush92 Avatar asked Dec 21 '17 13:12

Ankush92


1 Answers

if you compile it as a Script, groovyc will just ignore the final keyword, but if you wrap it into a class, groovyc will raise a compilation error.

fin.groovy with content

final String x = "a"
x = "b"

$ groovyc fin.groovy

Decompile it with ByteCodeViewer

import org.codehaus.groovy.reflection.*;
import java.lang.ref.*;
import groovy.lang.*;
import org.codehaus.groovy.runtime.*;
import org.codehaus.groovy.runtime.callsite.*;

public class fin extends Script
{
    private static /* synthetic */ SoftReference $callSiteArray;

    public fin() {
        $getCallSiteArray();
    }

    public fin(final Binding context) {
        $getCallSiteArray();
        super(context);
    }

    public static void main(final String... args) {
        $getCallSiteArray()[0].call((Object)InvokerHelper.class, (Object)fin.class, (Object)args);
    }

    public Object run() {
        $getCallSiteArray();
        String x = "a";
        return x = "b";
    }

    private static /* synthetic */ CallSiteArray $createCallSiteArray() {
        final String[] array = { null };
        $createCallSiteArray_1(array);
        return new CallSiteArray((Class)fin.class, array);
    }

    private static /* synthetic */ CallSite[] $getCallSiteArray() {
        CallSiteArray $createCallSiteArray;
        if (fin.$callSiteArray == null || ($createCallSiteArray = fin.$callSiteArray.get()) == null) {
            $createCallSiteArray = $createCallSiteArray();
            fin.$callSiteArray = new SoftReference($createCallSiteArray);
        }
        return $createCallSiteArray.array;
    }
}

There is no final anymore, and if you compile it with content

class A{
    final String x = "a"
    def a(){
        x = "b"
    }
}

It gives

$ groovyc fin.groovy 
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
fin.groovy: 4: cannot modify final field 'x' outside of constructor.
 @ line 4, column 3.
   x = "b"
   ^

1 error
like image 126
Yu Jiaao Avatar answered Oct 21 '22 01:10

Yu Jiaao