JEP 305 - Pattern Matching for instanceof (Preview)

Attila Kelemen attila.kelemen85 at
Sat Nov 23 18:42:02 UTC 2019


I have a couple of questions on the syntax of the upcoming
"instanceof" enhancement:

1. Can I write `obj instanceof String obj` and shadow the original
`obj` variable with the new one?

It would be nice if I could, because one of my main concern
with the lack of "auto-cast", is that I have to give another name
to the same thing, which usually leads to lame things like
`o` and `other`.

2. Is the newly declared variable final?

I personally would prefer if it would be final, because then
that is one less thing to worry about.

3. Is it legal to do this kind of declaration even if the effective
scope of that variable is nothing?

For example, `if (obj instanceof String s || myCondition)`.
As both path is reachable without `obj` being an instance of `String`.

4. What is the limit for the compiler to figure out the scope of the variable?

I was mildly surpised to see that `if (!(obj instanceof String s))`
works on the else path.

But this begs the question: What is the limit of the ability to
deduce the scope. If the previously mentioned expression works,
then I would naively expect that javac would evaluate it this way:
if the "instanceof expression" is false and the complete condition
might evaluate to true with any combination of true/false for the
other parts of the boolean expression, then then the newly declared
variable is not in scope for the true path (similarly for the else path).

If my above guess is true, then I would expect
`if (!(!(obj instanceof String s) || myCondition))`
to give me the `s` for the true path.

Attila Kelemen

More information about the compiler-dev mailing list