Java 8 Pattern Matching?

edarroyo picture edarroyo · Jun 27, 2012 · Viewed 22.4k times · Source

Will Java 8 support pattern matching like Scala and other functional programs do? I'm putting a presentation together of Java 8's Lambda features. I can't find anything on this particular Functional-programming concept.

I remember what got me interested in functional programming was the quicksort implementation, especially compared to imperative programming's implementation.

Answer

Konrad Reiche picture Konrad Reiche · Jun 30, 2012

I suppose you are not talking about pattern matching in the sense of applying a regular expression on a string, but as applied in Haskell. For instance using wildcards:

head (x:_)  = x
tail (_:xs) = xs

Java 8 will not support that natively, with Lambda expression there are, however, ways to do so, like this for computing the factorial:

public static int fact(int n) {
     return ((Integer) new PatternMatching(
          inCaseOf(0, _ -> 1),
          otherwise(  _ -> n * fact(n - 1))
     ).matchFor(n));
}

How to implement that you will find more information in this blog post: Towards Pattern Matching in Java.