Skip to content

Instantly share code, notes, and snippets.

Created January 9, 2018 01:18
Show Gist options
  • Save anonymous/0eea8d3768c571a9230f54fd31d43ba0 to your computer and use it in GitHub Desktop.
Save anonymous/0eea8d3768c571a9230f54fd31d43ba0 to your computer and use it in GitHub Desktop.
A demonstration of haskell-style pattern matching in java
public abstract class Maybe<V>
{
public abstract <T> T match(Function<V, T> some, Supplier<T> none);
public abstract void match(Consumer<V> some, Runnable none);
...
private static class Nothing<U> extends Maybe<U>
{
...
public <T> T match(Function<U, T> some, Supplier<T> none)
{
return none.get();
}
public void match(Consumer<U> some, Runnable none)
{
none.run();
}
...
}
private static class Just<V> extends Maybe<V>
{
final V value;
...
public <T> T match(Function<V, T> some, Supplier<T> none)
{
return some.apply(value);
}
public void match(Consumer<V> some, Runnable none)
{
some.accept(value);
}
...
}
@Zoybean
Copy link

Zoybean commented Jan 9, 2018

Example usage:

Maybe<Integer> m = someOperation();
m.match(
      (Integer value) -> System.out.println("value = " + value),
      () -> System.out.println("there is no value")
);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment