Variable not in scope after instanceof

Robbe Pincket robbepincket at live.be
Thu Apr 20 08:03:47 UTC 2023


Hi John,

To be honest I never fully read the rules on when pattern values are in scope or not, and just always assumed it matches my mental model of ‘the variable is in scope if it would be definite assigned here assuming the variable is definite assigned iff the match returned true’.

Using this assumption it is clear why this snippet wouldn’t work. `==` does not have any special rules about definite assignment when it’s arguments are boolean expressions and therefore falls back to the default of ‘A variable is definite assigned after the execution of a boolean expression if it is definite assigned both when true and false’

Hope this helps

Kind regards
Robbe Pincket


Van: John Hendrikx<mailto:hjohn at xs4all.nl>
Verzonden: donderdag 20 april 2023 9:21
Aan: amber-dev<mailto:amber-dev at openjdk.org>
Onderwerp: Variable not in scope after instanceof

I came across a bit of a curious way to check if something is not an instance of something, and I noticed it doesn't play along with the new instanceof construct that allows you to assign it to a local variable immediately:

    public static void main(String[] args) {
      Number n = 1.0;

      if (n instanceof Double d == false) {
        System.out.println("It was not a double");

        return;
      }

      System.out.println("It was a double: " + d);   // compile error
    }

In the above snippet, the variable "d", despite being accepted, is not in scope anywhere.

Changing the check to " !(n instanceof Double d)" works as expected.

Is this something that was missed, or am I misunderstanding why this can't work?

--John


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/amber-dev/attachments/20230420/6cdd2b9f/attachment.htm>


More information about the amber-dev mailing list