Different handing of "this" vs. "MyClass.this" in definite assignment
Archie Cobbs
archie.cobbs at gmail.com
Thu Dec 1 18:09:11 UTC 2022
This relates to JDK-8193904 <https://bugs.openjdk.org/browse/JDK-8193904>
(if amber-dev is the wrong place to ask about this please let me know;
here's an earlier thread
<https://mail.openjdk.org/pipermail/compiler-dev/2022-November/020899.html>
on compiler-dev).
The bug asks the question, should we change the JLS so that "MyClass.this"
is treated the same way as "this" with respect to definite assignment?
Here's how the compiler currently behaves:
// This class compiles without error
public class Example1 {
final int foo;
public Example1() {
System.err.println(Example1.this.foo); // no error generated here
this.foo = 42;
}
}
// This class fails to compile
public class Example2 {
private final int foo;
public Example2() {
Example2.this.foo = 42; // "cannot assign a value to final variable
foo"
}
}
Presumably the reason for the different treatment is because in general the
qualifying expression could be arbitrarily complex and the compiler can't
be expected to detect any possible qualification in front of "foo", so why
even start down that road?
For example, instead of
Example1.this = 42;
you could have:
((Example1)Function.<Object>identity().apply(this)).foo = 42;
Currently JLS §16 says:
> An access to its value consists of the simple name of the variable (or,
> for a field, the simple name of the field qualified by this) occurring
> anywhere in an expression except as the left-hand operand of the simple
> assignment operator = (§15.26.1
> <https://docs.oracle.com/javase/specs/jls/se19/html/jls-15.html#jls-15.26.1>).
>
>
Some options...
1. Deprecate the use of "MyClass.this" where "this" would work and start
generating a warning
2. Update JLS §16 to say "qualified by this or qualified by MyClass.this"
3. Do nothing and resolve JDK-8193904 as "Won't Fix"
4. ??
Thoughts?
-Archie
--
Archie L. Cobbs
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/amber-dev/attachments/20221201/c1838979/attachment.htm>
More information about the amber-dev
mailing list