Skip to content

Instantly share code, notes, and snippets.

@Superstar64
Last active December 10, 2021 04:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Superstar64/2d3f5e7973fcc8cc6501d5a63030762b to your computer and use it in GitHub Desktop.
Save Superstar64/2d3f5e7973fcc8cc6501d5a63030762b to your computer and use it in GitHub Desktop.
Typesafe Tagged Union in Java using Scott Encoding
// public domain
import java.util.function.Function;
interface Either<A, B> {
<C> C match(Function<A, C> left, Function<B, C> right);
}
class Left<A, B> implements Either<A, B> {
final A get;
Left(A get) {
this.get = get;
}
public <C> C match(Function<A, C> left, Function<B, C> right) {
return left.apply(get);
}
}
class Right<A, B> implements Either<A, B> {
final B get;
Right(B get) {
this.get = get;
}
public <C> C match(Function<A, C> left, Function<B, C> right) {
return right.apply(get);
}
}
public class Match {
public static void main(String[] args) {
Either<String, Integer> item = new Right<String, Integer>(5);
String normalized = item.match(x -> x, x -> x.toString());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment