Two new draft pattern matching JEPs
Brian Goetz
brian.goetz at oracle.com
Wed Mar 3 16:05:03 UTC 2021
> For me the section Pattern Matching and record classes is missing a discussion about the fact that even if the pattern uses a binding,
> the value of that binding is not accessed (so the corresponding record accessor is not called) until the binding is used at least once.
As attractive as that seems, I don't think we want to go there. There
are two big problems here.
1. Specifying in terms of accessors constrains our ability to evolve
the language -- in a direction we know we want to go, and soon. Just as
records get the obvious constructor if you don't give them one, they
also get the obvious _deconstructor_ if you don't give them one. But
surely, we might want to allow people to explicitly specify the
deconstructor, just as they can explicitly specify the constructor.
(The obvious implementation delegates to the accessors.) More
importantly, we want a "record pattern" to appeal to a deconstructor, so
it is useful for all classes, not just records, and we want the
semantics of such patterns to be consistent across records and classes,
to permit compatible refactoring. So a record pattern really has to be
a degenerate case of a deconstructor pattern. Giving the accessors more
billing than they deserve in this story just distracts from the real
star, which is deconstructors.
2. Specifying that we do not call the accessor unless / until the
binding is used effectively creates an expectation of laziness, which is
cool but which will be extremely difficult to maintain when we get to
more sophisticated patterns. And if record patterns are lazy but
everything else is not, that's just confusing. (And, worse, we are
spending our laziness budget where it matters least -- record accessors
are trivially inlined away 99% of the time, so the benefit of laziness
for records is almost zero.) Instead, we should specify that there is
no guarantee about the timing (or number of invocations) of the
accessor, and let the compiler generate the best code it can.
(I spent a lot of time trying to figure out how we can preserve the
option for laziness in complex patterns, and it generally falls apart
about when it would start to be valuable.)
More information about the amber-spec-observers
mailing list