Java Reference
In-Depth Information
switch (Expression) { case Constant : Statement ... }
with Scala's wildcard case playing the role of default: in Java. The main visible syntactic
difference is that Scala is expression-oriented whereas Java is more statement-oriented, but the
main expressiveness difference for the programmer is that Java patterns in case labels are
restricted to a couple of primitive types, enumerations, a few special classes that wrap certain
primitive types, and Strings. One of the biggest practical advantages of using languages with
pattern matching is that you can avoid using big chains of switch or if-then-else statements
interleaved with field-selection operations.
Here it's clear that Scala's pattern matching wins on ease of expressiveness over Java, and you
can only look forward to a future Java allowing more expressive switch statements. We make a
concrete proposal for this in chapter 16 .
In the meantime, let's see how Java 8 lambdas can provide an alternative way of achieving
pattern-matching-like code in Java. We describe this technique purely so you can see another
interesting application of lambdas.
Faking pattern matching in Java
First, let's consider just how rich Scala's pattern-matching match expression form is. For
example, the case
def simplifyExpression(expr: Expr): Expr = expr match {
case BinOp("+", e, Number(0)) => e
...
means “check that expr is a BinOp, extract its three components (opname, left, right), and then
pattern-match these components—the first against the String +, the second against the variable
e (which always matches), and then the third against the pattern Number(0).” In other words,
the pattern matching in Scala (and many other functional languages) is multilevel . Our
simulation of pattern matching using Java 8's lambdas will give only single-level pattern
matching; in the preceding example this would mean cases such as BinOp(op, l, r) or Number(n)
but not BinOp("+", e, Number(0)).
First, we make a slightly surprising observation. Now that you have lambdas, you could in
principle never use if-then-else in your code. You could replace code such as condition ? e1 : e2
with a method call:
myIf(condition, () -> e1, () -> e2);
 
Search WWH ::




Custom Search