Java Reference
In-Depth Information
f(0) = 1
f(n) = n*f(n-1) otherwise
In Java you would here write an if-then-else or a switch statement. Other languages have shown
that, for more complex data types, pattern matching can express programming ideas more
concisely compared to using if-then-else. For such data types, you might also use polymorphism
and method overriding as an alternative to if-then-else, but there's still language-design
discussion as to which is more appropriate. [ 9 ] We'd say that both are useful tools and you should
have both in your armory. Unfortunately, Java 8 doesn't have full support for pattern matching,
although we show how it can be expressed in chapter 14 . In the meantime, we illustrate with an
example expressed in the Scala programming language (another Java-like language using the
JVM that has inspired some aspects of Java evolution; see chapter 15 ) . Suppose you want to
write a program that does basic simplifications on a tree representing an arithmetic expression.
Given a data type Expr representing such expressions, in Scala you can write the following code
to decompose an Expr into its parts and then return another Expr:
9 The Wikipedia article on “expression problem” (a term coined by Phil Wadler) provides an
entry to the discussion.
Here Scala's syntax expr match corresponds to Java's switch (expr); don't worry about this code
for now—you'll read more on pattern matching in chapter 14 . For now, you can think of pattern
matching as an extended form of switch that can decompose a data type into its components at
the same time.
Why should the switch statement in Java be limited to primitive values and Strings? Functional
languages tend to allow switch to be used on many more data types, including allowing pattern
matching (in the Scala code, this is achieved using a match operation). In object-oriented design,
the visitor pattern is a common pattern used to walk through a family of classes (such as the
different components of a car: wheel, engine, chassis, and so on) and apply an operation to each
object visited. One advantage of pattern matching is that a compiler can report common errors
such as “Class Brakes is part of the family of classes used to represent components of class Car.
You forgot to explicitly deal with it.”
 
Search WWH ::




Custom Search