Java Reference
In-Depth Information
Somewhere, perhaps in a library, you'd have a definition (generic in type T):
static <T> T myIf(boolean b, Supplier<T> truecase, Supplier<T> falsecase) {
return b ? truecase.get() : falsecase.get();
}
The type T plays the role of result type of the conditional expression. In principle, similar tricks
can be done with if-then-else.
Of course, in normal code this would just make your code more obscure because if-then-else
perfectly captures this idiom. But we've noted that Java's switch and if-then-else don't capture
the idiom of pattern matching, and it turns out that lambdas can simply encode (single-level)
pattern matching—and rather more neatly than the chains of if-then-else.
Returning to pattern-matching values of class Expr, which has two subclasses, BinOp and
Number, you can define a method patternMatchExpr (again generic in T, the result type of the
pattern match):
interface TriFunction<S, T, U, R>{
R apply(S s, T t, U u);
}
static <T> T patternMatchExpr(
Expr e,
TriFunction<String, Expr, Expr, T> binopcase,
Function<Integer, T> numcase,
Supplier<T> defaultcase) {
return
(e instanceof BinOp) ?
binopcase.apply(((BinOp)e).opname, ((BinOp)e).left,
((BinOp)e).right) :
(e instanceof Number) ?
numcase.apply(((Number)e).val) :
defaultcase.get();
}
The result is that the method call
patternMatchExpr(e, (op, l, r) -> {return binopcode ;},
(n) -> {return numcode ;},
 
Search WWH ::




Custom Search