A function which derives its input from a delegate function which is invoked based on the result of a given predicate. This is the object oriented version of a switch expression. Unlike a switch expression though, it can take any predicate of the switched type. The downside is we can't enforce the expression to be exhaustive.
This is a simple example of how it would be used
Function<String,String> f = new Switch<>(
new Case<>(String::isEmpty, s -> "the String was empty"),
new Case<>(s -> s.length() == 1, s -> s + " contains a single character"),
new Default<>(s -> s + " is " + s.length + " characters long"));
If no case matches an IllegalArgumentException is thrown.
The names Switch, Case and Default are not carved in stone. Other names like Case, When and Else might work too (e.g. Ruby style).
A function which derives its input from a delegate function which is invoked based on the result of a given predicate. This is the object oriented version of a switch expression. Unlike a switch expression though, it can take any predicate of the switched type. The downside is we can't enforce the expression to be exhaustive.
This is a simple example of how it would be used
If no case matches an
IllegalArgumentException
is thrown.The names
Switch
,Case
andDefault
are not carved in stone. Other names likeCase
,When
andElse
might work too (e.g. Ruby style).