Pattern matching on Class<T>
Nathan Reynolds
numeralnathan at gmail.com
Sat Jun 11 13:18:12 UTC 2022
I have hit this same idea several times in the past 2 weeks. I too would
like to switch on Class.
On Sat, Jun 11, 2022 at 6:06 AM Vikram Bakshi <vab2048 at gmail.com> wrote:
> Hello,
>
> Apologies if code formatting does not appear well (I'm not used to mailing
> lists). All code blocks are available to view here:
> https://stackoverflow.com/questions/72545671/pattern-matching-on-classt
>
> I asked a question on stackoverflow about why we cannot match on Class<T>
> in the way I expect. Suppose we have:
>
> sealed interface Animal permits Dog, Cat, Bear {}
> record Dog() implements Animal {}
> record Cat() implements Animal {}
> record Bear() implements Animal {}
>
> This would work:
>
> static <T extends Animal> String makeNoise(Class<T> cls) {
> if(cls.equals(Dog.class)) {
> return "WOOF";
> } else if(cls.equals(Cat.class)) {
> return "MEOW";
> } else if(cls.equals(Bear.class)) {
> return "ROAR";
> } else {
> throw new IllegalStateException("Unknown state");
> }
> }
>
> But this wouldn't:
>
> static <T extends Animal> String makeNoisePatternMatch(Class<? extends
> Animal> cls) {
> return switch(cls) {
> case Dog.class c -> "WOOF";
> case Cat.class c -> "MEOW";
> case Bear.class c -> "ROAR";
> };
> }
>
> I got the answer on Stack Overflow that this is not allowed by the spec. My
> question to the mailing list is: will the current restriction be lifted in
> the future?
>
> Will we be able to pattern match like the above? And if not - how come it
> is restricted (I'm not criticising but rather just asking more out of
> curiosity to understand the decision to maintain the restriction)?
>
> Regards,
>
More information about the amber-dev
mailing list