Reporting of pattern variable redefinition

Gavin Bierman Gavin.Bierman at oracle.com
Wed Jan 27 16:45:26 UTC 2021


Hi Jay,

This stuff is subtle! It isn’t a bug actually, but a deliberate design decision. The place to look is 6.3.1.4 of the draft spec (http://cr.openjdk.java.net/~gbierman/jep394/jep394-20210108/specs/patterns-instanceof-jls.html#jls-6.3.1.4 <http://cr.openjdk.java.net/~gbierman/jep394/jep394-20210108/specs/patterns-instanceof-jls.html#jls-6.3.1.4>)

You’ll see at the end of that section a list of compile-time errors, the first error actually covers your example.

Your next question is probably, “But why, Gavin?”. Here’s the thinking. We decided not to allow pattern variable declarations to syntactically appear twice but in ways where exactly one will be executed. Here’s an example:

	e ? (o instanceof String s) : (o instanceof String s)

Note here, no matter the value of e, always one of the pattern variables will be initialised by pattern matching. So, we could have allowed this, but we decided not to. (At least not for now.) If we had supported it, then we would have to break some very deep-rooted assumptions in the language about declarations. We would have a Java where, depending on your viewpoint, declarations can be bifurcated or merged. We must thought that was too strange and unlike the Java we love today. (Imagine asking your IDE for the declaration of a variable, and seeing several things highlighted!?)

So, to your example, the compiler is not complaining because it thinks “a” is in scope in the false arm - try (o instanceof String a) ? false : ( a == “hello”) and you’ll see that isn’t the case, but because it sees that you are trying to merge the two declarations of the String a pattern variable.

Hope this helps!
Gavin

> On 27 Jan 2021, at 13:58, Jayaprakash Artanareeswaran <jay.a at outlook.in> wrote:
> 
> Hello,
> 
> I am looking at the following code and wondering why Javac (from JDK 16, ea33) reports an error on the first line and not on the second:
> 
> boolean b1 = (o instanceof String a) ? false : (o instanceof String a); // Error 
> boolean b2 = (o instanceof String a) ? false : ((o instanceof String a) ? false : true); // No error
> 
> Is reporting the first case required as the pattern variable "a" is not in scope in the false arm of the conditional expression anyway?
> 
> Regards,
> Jay

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


More information about the compiler-dev mailing list