Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Switch function #250

Open
dmfs opened this issue Jan 2, 2020 · 0 comments
Open

Switch function #250

dmfs opened this issue Jan 2, 2020 · 0 comments

Comments

@dmfs
Copy link
Owner

dmfs commented Jan 2, 2020

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant