/ Groovyの "final"キーワード - groovy

Groovyの 'final'キーワード - groovy

これはGroovyの人々によるバグか意図的な設計の決定ですか?

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

あなたはこれを実行し、問題なく動作します。代わりに実行時例外をスローする必要がありますか?クラスに注釈を付ける @CompileStatic どちらも助けてくれませんでした。 @CompileStatic 使用されている。

回答:

回答№1は2

それをコンパイルすると Script, groovyc ただ無視する final あなたはそれをクラスにラップすると、 groovyc コンパイルエラーが発生します。

コンテンツを含むfin.groovy

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

$ groovyc fin.groovy

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;
}
}

ない final もう、 それをコンテンツでコンパイルすると

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

それは与えます

$ 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