[records] Compile-time constants can be used in local classes static members but cannot be used in records

Tagir Valeev amaembo at gmail.com
Wed Jan 29 03:01:16 UTC 2020


Hello!

This code is perfectly compilable (javac 14-ea+33-1439):

public class RecordTest {
    public static void main(String[] args) {
        final int x = 2;
        class X {
            static final int y = x;
        }
    }
}

This is not (simply changed class to record, leaving everything else the same):

public class RecordTest {
    public static void main(String[] args) {
        final int x = 2;
        record X() {
            static final int y = x;
        }
    }
}

Error:(5, 34) java: non-static variable x cannot be referenced from a
static context

This looks counter-intuitive to me: why static field in one case can
refer to compile-time constant and in another case cannot?

With best regards,
Tagir Valeev


More information about the amber-dev mailing list