Quick question regarding pattern matching

Brian Goetz brian.goetz at oracle.com
Fri Mar 24 15:50:50 UTC 2017


>
> Good to know, thanks. I had a feeling that the nestmates proposal would
> be involved (from our conversation on the valhalla list a while back).
>
> As far as I can tell, current matching implementations in languages
> handle the binary incompatibility case you mentioned by synthesizing
> bytecode that raises an unchecked exception such as MatchException as a
> fallback. I don't think I covered this specifically in that article I
> wrote[0] but it's fairly apparent from the bytecode samples.

Yes, though this is tricky.  For a switch *statement*, there is no 
requirement that the case list be exhaustive -- and in general, we rely 
on DA/DU to catch errors like this.  It's perfectly reasonable to say

     Object o = ...
     switch (o) {
         case String s: println("It's a string");
     }

which is really equivalent to

     if (o instanceof String)
         println("It's a string");

OTOH, for a switch *expression*, you have to have a value for all 
cases.  If the compiler knows the switch isn't exhaustive (today, that 
means "no default case"), it would have to raise an error; if it thinks 
it is exhaustive, but its possible exhaustiveness could be undermined by 
separate compilation, it should probably insert a catch-all default 
which throws an informative exception.  (Which will usually be far more 
informative than the kinds of "default: throw new AssertionError("logic 
fail")" exceptions that humans write by hand.)

But again, we're getting ahead of ourselves :)

>
> I think it's important to keep in mind that algebraic data types aren't
> necessarily value types (if value type is taken to mean all-immutable
> fields with no identity) so it's nice to be able to keep the discussion
> somewhat separate from the Valhalla work via Amber. Just being able to
> give Scala and Kotlin the few sealing primitives they need instead of
> having to rely on proprietary annotations would go a long way towards
> improving matters, I think.
>

Very interested in hearing the arguments for mutability in GADTs -- when 
the gate for such discussions opens :)

Cheers,
-Brian


More information about the amber-dev mailing list