dmfs / jems

Java gems, a collection of Java utilities.
Apache License 2.0
5 stars 2 forks source link

Switch function #250

Open dmfs opened 4 years ago

dmfs commented 4 years ago

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).