public class OneOf2<A,B> extends Object
union.typeMatch(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.
union.typeMatch(fst -> fst.doOneThing(),
sec -> { throw new IllegalStateException("Asked for a 2nd; only had a 1st."); });
As a shortcut, you can call (using method references) union::throw1 or union::throw2
union.typeMatch(fst -> fst.doOneThing(),
union::throw2);
For the shortest syntax and best names, define your own subclass. This is no where near as
elegant as sub-classing Tuples.
public class A_Or_B extends OneOf2<ClassA,ClassB> {
// Constructor
A_Or_B(ClassA cre, ClassB rev, int s) { super(cre, rev, s); }
// Static factory method for first type
public static A_Or_B fst(ClassA cre) {
return new A_Or_B(cre, null, 1);
}
// Static factory method for second type
public static A_Or_B sec(ClassB rev) {
return new A_Or_B(null, rev, 2);
}
// Return first or throw exception
public ClassA fst() {
return typeMatch(cre -> cre,
super::throw2);
}
// Return second or throw exception
public ClassB sec() {
return typeMatch(super::throw1,
rev -> rev);
}
}
Now you use descriptive and extremely brief syntax:
union.fst().doOneThing();
| Modifier | Constructor and Description |
|---|---|
protected |
OneOf2(A a,
B b,
int s) |
Copyright © 2017. All rights reserved.