bye stable values, enter lazy constants
    Maurizio Cimadamore 
    maurizio.cimadamore at oracle.com
       
    Fri Oct  3 09:08:16 UTC 2025
    
    
  
On 03/10/2025 00:40, Sergey Bylokhov wrote:
> On 10/2/25 01:17, Maurizio Cimadamore wrote:
>
>> Yep. Thinking more about this, if we ever did the idea you suggested the
>> other day (e.g. declaring static fields inside a method), then you could
>> have tighter scoping
>>
>> e.g.
>>
>> ```
>> Logger getLogger() {
>>      static LazyConstant<Logger> LOGGER = LazyConstant.of(...);
>>      return LOGGER.get();
>> }
>> ```
>>
>> (Now, while I think it's useful to have static _classes_ inside a
>> method, I think having a static field in there might be a bit confusing,
>> as it looks like a local variable, but isn't really -- it's a field. So
>> whether that's a good idea or not will have to be assessed separately)
>
>
> Note that using LazyConstant in the example above is actually 
> unnecessary, a simpler version works just as well:
>
> Logger getLogger() {
>    static Logger LOGGER = ...;
>    return LOGGER;
> }
>
> So, if there are any plans to implement this in the future, we should 
> ensure it does not duplicate what LazyConstant provides. It is 
> possible that the new static local variables combined with the new 
> VarHandle access modes will cover most use cases or we can fit 
> LazyConstant somewhere in between.
I think that would largely depend on what having a static field inside a 
method means.
I can imagine it being translated in at least 3 different ways:
* as a plain static final in the enclosing class
* as a mutable static in the enclosing class
* as a final field in a hidden local class generated by javac
Each translation has different properties. But, frankly, none of them 
look like a slamdunk in terms of explaining to developers what the code 
above means. (But, please, let's not turn this thread into one on static 
declarations inside methods).
Maurizio
    
    
More information about the leyden-dev
mailing list