Skip to content

Instantly share code, notes, and snippets.

@alwins0n
Last active December 8, 2018 12:32
Show Gist options
  • Save alwins0n/b61ccd3ecbadfbd508a9dad600cfa268 to your computer and use it in GitHub Desktop.
Save alwins0n/b61ccd3ecbadfbd508a9dad600cfa268 to your computer and use it in GitHub Desktop.
Alwins Pattern Matchin Gist
import org.junit.Test;
public class AdtTest {
@Test
public void testStuff() {
MyAdt adt = new MyBar();
String result = adt.match(
(foo) -> "do with foo",
(bar) -> "do with bar"
);
System.out.println(result);
}
}
import java.util.function.Consumer;
public interface MyAdt {
interface MyAdtMatcher<R> {
R with(MyFoo foo);
R with(MyBar bar);
}
<R> R match(MyAdtMatcher<R> matcher);
default <R> R match(Function<MyFoo, R> matchFoo, Function<MyBar, R> matchBar) {
return match(new MyAdtMatcher<R>() {
@Override
public R with(MyFoo foo) {
return matchFoo.apply(foo);
}
@Override
public R with(MyBar bar) {
return matchBar.apply(bar);
}
});
}
default void match(Consumer<MyFoo> matchFoo, Consumer<MyBar> matchBar) {
match(new MyAdtMatcher<Void>() {
@Override
public Void with(MyFoo foo) {
matchFoo.accept(foo);
return null;
}
@Override
public Void with(MyBar bar) {
matchBar.accept(bar);
return null;
}
});
}
}
public class MyBar implements MyAdt {
@Override
public void match(MyAdtMatcher matcher) {
matcher.with(this);
}
}
public class MyFoo implements MyAdt {
@Override
public void match(MyAdtMatcher matcher) {
matcher.with(this);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment