Pattern Matching for Switch Expressions feedback
Brian Goetz
brian.goetz at oracle.com
Wed Oct 20 23:35:19 UTC 2021
This comes from the current limitations of generics. Generics in Java
are checked at compile time, and then erased -- the runtime only knows
about List, not List<String> vs List<Integer>. So there is no way to
dynamically test whether a given List is a List<Integer> vs a
List<String>, which is what a pattern would have to do.
We do take generic information into account in type checking; if you
have a switch over a List<String>, we can immediately reject
ArrayList<Integer> as a possible type test, but know that
ArrayList<String> is possible. But if you are switching over a List<?>
or a raw List, there's simply nothing we can do (today) to dynamically
dispatch the switch.
Project Valhalla will eventually bring some progress to this, but by way
of expectation setting, this problem is several orders of magnitude
bigger than pattern matching, and even then, there will be some
limitations that stem from migration compatibility.
On 10/20/2021 7:11 PM, Nir Lisker wrote:
> Hi,
>
> I've used pattern matching in switch expressions in my codebase. While my
> use cases are simple (no need to deal with nulls and ordering due to 2
> patterns potentially matching), I can say that it works well. My biggest
> request is to be able to differentiate between parametric types:
>
> case List<Integer> -> ...
> case List<String> -> ...
>
> I've seen some discussion on this previously on the mailing list, but not a
> conclusion. Is this something that can be addressed in this JEP? Is it
> planned for a future change outside of this JEP?
>
> - Nir
More information about the amber-dev
mailing list