Record pattern and enhanced for
Remi Forax
forax at univ-mlv.fr
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
https://cr.openjdk.java.net/~gbierman/jep432%2b433/jep432+433-20221018/specs/patterns-switch-record-patterns-jls.html#jls-14.14.2
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
System.out.println(value);
}
but you can not write
I i = ...
for(Impl impl : List.of(i)) { // use a type declaration, does not compile !
System.out.println(impl.value());
}
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.
regards,
Rémi
More information about the amber-spec-observers
mailing list