I started to play with the new Java 21 feature - pattern matching.
public class Main {
public static void main(String[] args) {
RecordB recordB = new RecordB(true);
switch(recordB) {
case RecordB b when b.bool() -> System.out.println("It's true");
case RecordB b when !b.bool() -> System.out.println("It's false");
}
}
record RecordB(boolean bool) { }
}
When compiling the code above, the compiler yields information that the switch statement does not cover all possible input values
This is not necessarily true from my perspective. So here is my question: does any guarded pattern always make the switch expression non-exhaustive for the compiler or I am missing something here?
case null, default -> {}
, but, for the matter, evendefault -> {}
alone "solves" it. – Umbrelladefault
case just happens to be mentioned in the specs I linked. – Umbrellacase null, default
. I posted it to reply to (part) of your comment "... not sure if that is what lealceldeiro mentions in his answer...". As you correctly clarifiedcase null -> { }
does not solve the problem. And then I mentioned that thiscase null, default
is what is officially stated in the JLS. Again, I agree with you: just adding adefault
to this code defeats the purpose of the question. – Umbrellacase RecordB(var b) when b -> …
andcase RecordB(var b) when !b -> …
– Brassywhen
predicates and figure out that things likex>0
andx<=0
together are exhaustive. While this would be nice, this is impossible in the general case (see, e.g. Rice's theorem), and the boundary between what an arbitrarily smart algorithm can figure out or not would be complicated and surprising to users. So we instead opted to draw a simple, bright line, rather than navigating a fractal boundary (likely iteratively). – Abad