Directly initialized final field is not constant folded later when prefix with "this"

Brian Goetz brian.goetz at oracle.com
Mon Jun 29 14:01:58 UTC 2020


It goes back to the why we define constant expressions at all.  The goal 
in defining constant expression, and allowing certain 
static-compile-time optimizations regarding constant expressions, was 
_not_ to support every possible optimization that could be imagined 
regarding constants -- far from it.  It was to define a simple, easy to 
understand rule to address the most obvious of foldable constants, such 
as `1 + 1`, or `1 + staticFinalField`.

Sure, we could patch this particular corner case, but where's the 
benefit?  So we can encourage people to use this long-discouraged 
idiom?  And, the more complex we make the definition of compile-time 
constant, the more new corner cases we create, the harder it is to 
reason about, and the more likely the _next_ corner case that comes 
along will say "well, you did it for `this.x`, and this is 10x more 
important, so ..."  Fast forward, and this rule has 100 clauses.  No 
thank you!

Bottom line: there's negative value in changing it now.  The balance 
might have been different in 1995, but were I in that room, I would 
probably still draft it this way.

On 6/11/2020 3:18 PM, Roland Illig wrote:
> > A constant expression is ...
> >
> > *  Simple names (§6.5.6.1) that refer to constant variables
> >    (§4.12.4).
> >
> > *  Qualified names (§6.5.6.2) of the form TypeName.Identifier
> >    that refer to constant variables (§4.12.4).
>
> I wouldn't have expected that this makes a difference, but since `this`
> is not a TypeName, the compiler works as specified.
>
> This leaves the question why `this.field` was not defined to be
> equivalent to the unqualified `field` in the first place? Can anyone
> shed a light on this? 

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.java.net/pipermail/compiler-dev/attachments/20200629/c6f62f44/attachment.htm>


More information about the compiler-dev mailing list