Other ways to use destructuring

Brian Goetz brian.goetz at oracle.com
Mon Apr 3 12:22:55 UTC 2023


> In thinking about record destructuring it occurs to me it could be 
> used in more places than currently proposed.
>

Yes, these are what we've been calling "imperative destructuring", where 
an exhaustive pattern can be used in a non-conditional context.  There 
was a hint of this in the experimental use of record patterns in foreach 
loops, we've talked about a `let` or `match` statement a fair bit, and 
have briefly discussed using destructuring in method headers (though we 
are pretty negative on that one right now.)

We're being deliberately conservative about this; right now it feels 
like it's in the "because we can" stage, and that's where mistakes come 
from.  We will revisit when we nail down the declaration story for 
matchers, since these are likely to come back into play when we address 
matcher implementations delegating to other matchers (analogous to 
"super" calls in constructors.)

>
> One example would be in a function call:
>
>
> record HumanName(firstName: String, middleName: String, lastName: 
> String) {}
>
> HumanName humanName = new HumanName(“Alice”, “Bateman”, “Chandler”);
>
>
> String getFormattedName(humanName: HumanName(firstName, _, lastName))
>
> {
>
>    return lastName + “, “ + firstName;
>
> }
>
>
> final String fmtName = getFormattedName(humanName);
>
>
>
> another could be in a for loop
>
>
> final Set<HumanName> humans = new HashSet<>();
>
> humans.add(humanName);
>
> for (final humanName: HumanName(firstName, _, lastName): humans)
>
> {
>
> processFirstName(firstName);
>
> processLastName(lastName);
>
>    ...
>
> }
>
>
> or indeed in any body
>
>
> with humanName as HumanName(firstName, _, lastName)
>
> {
>
> processFirstName(firstName);
>
> processLastName(lastName);
>
>    ...
>
> }
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/amber-dev/attachments/20230403/dfbcec4a/attachment-0001.htm>


More information about the amber-dev mailing list