Record pattern and enhanced for

Remi Forax forax at
Mon Oct 24 16:53:32 UTC 2022

Hi do not think we have yet discussed about using the record pattern in an enhanced for

My first reaction when reading that part of the spec was, ok, cool, a bit weird to not piggyback it on pattern assignment but on the switch instead.
But this morning in the shower, it was more, wait a minute ... it means that a record pattern and a type declaration using the same type do not work the same.

For example, with a sealed interface I and a record Impl(int value), it's sole implementation.

  With the proposed semantics, you can write
     I i = ...
     for(Impl(var value) : List.of(i)) {  // use a record pattern
   but you can not write
     I i = ...
     for(Impl impl : List.of(i)) {       // use a type declaration, does not compile !

  I hope we can keep the invariant that a record pattern and a variable declaration with the same type should both work the same way.

There is also a minor issue that looks like an overlook but refactoring an exhanced for from using a declaration to a record pattern is a little dangerous because if the iterable is null the semantics change, with the record pattern it throws a MatchException instead of a NPE.


More information about the amber-spec-experts mailing list