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

Vicente Romero vicente.romero at oracle.com
Wed Jan 29 03:39:38 UTC 2020


Hi Tagir,

This behavior is in accordance with the spec: a local record is not a 
local class, local records are not allowed to capture any state from its 
enclosing type. We plan to revisit this in the future not only for 
record but as a general effort on nested-ness but for the time being we 
preferred to let local records immune to any capture rule that applies 
to local classes

Vicente

On 1/28/20 10:01 PM, Tagir Valeev wrote:
> 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