Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8287667

14.30.2: Pattern matching for any pattern is incorrect

XMLWordPrintable

    • Icon: Enhancement Enhancement
    • Resolution: Incomplete
    • Icon: P4 P4
    • None
    • 19
    • specification

      In 14.30.2 the semantics of pattern matching for any patterns is incorrect. It is defined as:

      - A value *v* (including the null reference) *matches* an any pattern.
          The pattern variable declared by the any pattern is initialized to *v*.

      This means that for a switch such as:

          switch (o) {
              case null, String s -> System.out.println(“String”);
              case Object o1 -> System.out.println(“Object”);
          }

      the first label will match everything (as it is resolved to an any pattern), even when `o` is `new Object()`.

      This is clearly wrong. The semantics of an any pattern should be:

      - The null reference *matches* an any pattern.

          The pattern variable declared by the any pattern is initialized to the null reference.

      - A value *v* that is not the null reference *matches* an any pattern of type
          *T* if *v* can be cast to *T* without raising a `ClassCastException`; and
          *does not match* otherwise.
          
          If *v* matches, then the pattern variable declared by the any pattern is
          initialized to *v*.
          
          If *v* does not match, then the pattern variable declared by the any
          pattern is not initialized.

      This reflects the intended semantics that any patterns behave like a nullable type pattern.

            gbierman Gavin Bierman
            gbierman Gavin Bierman
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated:
              Resolved: