public class OneOf2<A,B> extends Object
Tuple2.
OneOf2 is designed to be sub-classed so you can add descriptive names. The safest way
to use Union classes is to always call match() because it forces you to think about how to
handle each type you could possibly receive.
Usage:
thingy.match(fst -> fst.doOneThing(),
sec -> sec.doSomethingElse());
Sometimes it's a programming error to pass one type or another and you may want to throw an
exception.
oneOf.match(fst -> fst.doOneThing(),
sec -> { throw new IllegalStateException("Asked for a 2nd; only had a 1st."); });
For the shortest syntax and best names, define your own subclass. This is similar to sub-classing Tuples.
static class String_Integer extends OneOf2<String,Integer> {
// Private Constructor because the o parameter is not type safe.
private String_Integer(Object o, int n) { super(o, String.class, Integer.class, n); }
// Static factory methods ensure type-safe construction.
public static String_Integer ofStr(String o) { return new String_Integer(o, 0); }
public static String_Integer ofInt(Integer o) { return new String_Integer(o, 1); }
}
equals(), hashcode(), and toString() are all taken care of for you.
Now you use descriptive and extremely brief syntax:
// Type-safe switching - always works at runtime.
x.match(s -> (s == null) ? null : s.lowerCase(),
n -> "This is the number " + n);
// If not a String at runtime throws "Expected a(n) String but found a(n) Integer"
x.str().contains("goody!");
// If not an Integer at runtime throws "Expected a(n) Integer but found a(n) String"
3 + x.integer();
| Modifier | Constructor and Description |
|---|---|
protected |
OneOf2(Object o,
Class<A> aClass,
Class<B> bClass,
int index)
Protected constructor for subclassing.
|
protected OneOf2(Object o, Class<A> aClass, Class<B> bClass, int index)
o - the itemaClass - class 0 (to have at runtime for descriptive error messages and toString()).bClass - class 1 (to have at runtime for descriptive error messages and toString()).index - 0 means this represents an A, 1 represents a B, 2 represents a C, 3 means Dpublic <R> R match(Fn1<A,R> fa, Fn1<B,R> fb)
fa - the function to be executed if this OneOf stores the first type.fb - the function to be executed if this OneOf stores the second type.Copyright © 2019. All rights reserved.