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

Implement javac changes for deconstruction patterns.

XMLWordPrintable

    • Icon: CSR CSR
    • Resolution: Unresolved
    • Icon: P3 P3
    • None
    • tools
    • None
    • source
    • minimal
    • Language construct
    • SE

      Summary

      Under JEP 305 (https://bugs.openjdk.java.net/browse/JDK-8181287), pattern matching for instanceof has been added as a preview feature, together with a support for type test patterns, like:

      ... o is a variable declared with a general type such as Object ...
      if (o instanceof <type> v) {
          ... use the newly declared variable v
              which refers to the same object as o
              but with a more specific type ...
      }

      Herein, we propose to a) preserve the pattern matching in instanceof feature, and the type test patterns, as a preview for JDK 15; b) add a new type of patterns, the deconstruction patterns.

      The deconstruction patterns will allow to split record types into their components, like:

      ... o is a variable declared with a general type such as Object ...
      if (o instanceof <record-type>(var component1, var component2)) {
          ... use the newly declared variables component1 and component2
              which refer to the components of <record-type>
      }

      Problem

      Access to record components using accessors may be inconvenient/verbose in some cases. Being able to dismantle the record in one step to components will be useful.

      Solution

      The proposed changes are twofold: a) the current preview feature - pattern matching in instanceof and type test patterns will remain a preview feature in JDK 15 b) a new kind of patterns is added - the deconstruction patterns. These will allow to dismantle record into their components in one step. This will be part of the preview feature as well.

      As a corollary of the implicit nature of the deconstruction patterns for records, it will currently be at least a source-incompatible change to add a new or remove existing state component to or from a record. The pre-existing deconstruction patterns in the source code will then use an incorrect number of components, and will not compile. Reordering state components will face similar issues.

      Specification

      The current draft of the JLS change, and the diff for the corresponding API changes are attached. For convenience, the JLS draft can also be found here: http://cr.openjdk.java.net/~gbierman/jep375/jep375-20200316/specs/patterns-instanceof-jls.html

            jlahoda Jan Lahoda
            jlahoda Jan Lahoda
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated: