With the new Java 21 features, we have better Pattern Matching. With these features, we have guarded pattern case labels, where one can define a pattern guard for case labels that looks like the following:
switch (someObject) {
case String s when someVar == 5 -> {}
case Integer i when someVar == 10 -> {}
//...//
}
Why, in the example above, must someVar
be final or effectively final? Is it so that we can't reassign the value in a seperate case that would make our case pass/fail differently than if we had not reassigned it? I could not find the relevant information digging through the JEP but if someone can point me to it that'd be great!
Because the meaning of the switch -- which is code -- should be constant. It should not be sensitive to changes in the values of local variables. Of course, you are free to blow this up using calls to methods whose behavior changes from invocation to invocation -- thank you, pervasive mutability -- but you shouldn't. Doing so makes switches harder to understand (and harder to optimize.)