Last active
December 10, 2021 04:55
-
-
Save Superstar64/2d3f5e7973fcc8cc6501d5a63030762b to your computer and use it in GitHub Desktop.
Typesafe Tagged Union in Java using Scott Encoding
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 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