Last active
December 8, 2018 12:32
-
-
Save alwins0n/b61ccd3ecbadfbd508a9dad600cfa268 to your computer and use it in GitHub Desktop.
Alwins Pattern Matchin Gist
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
}); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class MyBar implements MyAdt { | |
@Override | |
public void match(MyAdtMatcher matcher) { | |
matcher.with(this); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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