Reputation: 171
Wrt to Java pattern matching (JEP 441), if I am matching an object using a switch statement, like this:
switch (cases) {
case A(
B b,
C c,
D d,
) -> doSomething();
}
How can I match the class C
to any subclass of C
without explicitly enumerating each subclass? i.e
switch (cases) {
case A(
B b,
C c,
D d,
) -> doSomething();
case A(
B b,
CVariantOne c, // I dont want to do this
D d,
) -> doSomething();
}
I want to match the c
field regardless of which subclass of C
it is, but without having to specify each possible subclass individually.
Otherwise, I would need to account for all possible subclasses of C
which becomes a problem if I also need to enumerate B
and its subclasses.
I understand something similar is mentioned under the "future works" section. However, what are my alternatives for now ?
Upvotes: 0
Views: 61
Reputation: 21630
It would be very strange if you had to enumerate all subclasses: what if someone replaces the class C
from your example with an interface like CharSequence
that can be implemented by classes that the compiler doesn't even know about?
Note that with Java 21 your example only works if A
is a record (this is specified in JEP 440).
The "future works" section in JEP 441 is about expanding the deconstruction matching (like the one specified for records in JEP 440) to general classes.
Upvotes: 3