Java Reference
In-Depth Information
do you declare x to have type Car or Vehicle? In this case a simple explanation that the missing
type is the type of the initializer (here Vehicle) is perfectly clear, and it can be backed up with a
statement that var may not be used when there's no initializer.
16.2.3. Pattern matching
As we discussed in chapter 14 , functional-style languages typically provide some form of pattern
matching—an enhanced form of switch—in which you can ask, “Is this value an instance of a
given class?” and, optionally, recursively ask whether its fields have certain values.
It's worth reminding you here that traditional object-oriented design discourages the use of
switch and instead encourages patterns such as the visitor pattern where data-type-dependent
control flow is done by method dispatch instead of by switch. This isn't the case at the other end
of the programming language spectrum—in functional-style programming where pattern
matching over values of data types is often the most convenient way to design a program.
Adding Scala-style pattern matching in full generality to Java seems quite a big job, but
following the recent generalization to switch to allow Strings, you can imagine a more-modest
syntax extension, which allows switch to operate on objects, using the instanceof syntax. Here
we revisit our example from section 14.4 and assume a class Expr, which is subclassed into
BinOp and Number:
switch (someExpr) {
case (op instanceof BinOp):
doSomething(op.opname, op.left, op.right);
case (n instanceof Number):
dealWithLeafNode(n.val);
default:
defaultAction(someExpr);
}
There are a couple of things to note. We steal from pattern matching the idea that in case (op
instanceof BinOp):, op is a new local variable (of type BinOp), which becomes bound to the
same value as someExpr; similarly, in the Number case, n becomes a variable of type Number.
In the default case, no variable is bound. This proposal avoids much boilerplate code compared
with using chains of if-then-else and casting to subtype. A traditional object-oriented designer
would probably argue that such data-type dispatch code would better be expressed using
visitor-style methods overridden in subtypes, but to functional-programming eyes this results in
 
Search WWH ::




Custom Search