It is possible to handle this using Vavr library
import static io.vavr.API.*;
import static io.vavr.Predicates.*;
Match(variable).of(
Case($(isIn(5, 6, ... , 100)), () -> doSomething()),
Case($(), () -> handleCatchAllCase())
);
This is of course only slight improvement since all cases still need to be listed explicitly. But it is easy to define custom predicate:
public static <T extends Comparable<T>> Predicate<T> isInRange(T lower, T upper) {
return x -> x.compareTo(lower) >= 0 && x.compareTo(upper) <= 0;
}
Match(variable).of(
Case($(isInRange(5, 100)), () -> doSomething()),
Case($(), () -> handleCatchAllCase())
);
Match is an expression so here it returns something like Runnable
instance instead of invoking methods directly. After match is performed Runnable
can be executed.
For further details please see official documentation.