Java 13 Pattern Matching Feature Explained

Author: Shazin Sadakath


We have talked about Java 13 features in previous posts and today we are going to look at a more advanced and useful we can expect to be released with Java 13. Namely this feature is called Pattern Matching (JEP 305). This feature solves a very common and error prone coding style many Java developers have been painstakingly using for quite sometime now. 

Ever seen the following code?

if (o instanceof String) {
    int length = ((String) o).length();
    // Use length
}

This code may look very simple because many Java developers are familiar with it, but this code is boilerplate as casting has nothing to do with business logic and has many potential areas for bugs to hide. What if we can write the same code as below;

if (o instanceof String s) {
    int length = s.length();
    // Use length
}

Within the above if statement, we are doing Pattern Matching. A pattern fuses testing, conditional extraction, and binding to variables in a single statement. Thus the desclaration String s, becomes a block scoped variable within the if block. You may think this is not a big deal, How about with the following code?

public boolean equals(Object o) {
    if (o instanceof Apple) {
        Apple a = (Apple) o;
        return this.size == a.size
               && Objects.equals(this.color, a.color);
    }
    return false;
}

The above code also has a lot of places for bugs to hide unintentionally. But following equals implementation with Pattern Matching reduces the chances for bugs drastically.

public boolean equals(Object o) {
    return (o instanceof Apple a)
        && this.size == a.size
        && Objects.equals(this.color, a.color);
}

Also Pattern Matching can be used with newly introduced Java feature switch expression and statements as below;

String styled;
switch (obj) {
    case Integer i:
        styled = String.format("int %d", i);
        break;
    case Byte b:
        styled = String.format(“byte %d", b);
        break;
    case Long l:
        styled = String.format(“long %d", l);
        break;
    case Double d:
        styled = String.format(“double %f", d);
        break;
    case String s:
        styled = String.format("String %s", s);
        break;
    // Short, Character, Float, Boolean
    default:
        styled = "unknown";
}

In the above code snippet constant obj is of type object and using it as any reference Number type requires type casting. But with Pattern Matching that requirement is no longer there. Also the code can be made more concise as below with switch expression;

String styled =
switch (obj) {
    case Integer i -> String.format("int %d", i);
    case Byte b -> String.format(“byte %d", b);
    case Long l -> String.format(“long %d", l);
    case Double d -> String.format(“double %f", d);
    case String s -> String.format("String %s", s);
    // Short, Character, Float, Boolean
    default -> "unknown";
} 

The Pattern Matching feature seems to look like a time saver for Java developers and Oracle Java Engineers are working on novel ways to make use of this feature with other new features like Records, Sealed Types and Deconstruction Patterns which enables code like following;

if (geo instanceof GeoPoint(var lat, var long)) {
    // Use lat, long
}

The GeoPoint in this case will be a Record and can be deconstructed to transform its state variables to local variables. These features will come out with Java 13 and it is going to exciting times for Java Developers.



Tags: Java13 PatternMatching Records SealedTypes DeconstructionPattern
Views: 285
Register for more exciting articles

Comments

Please login or register to post a comment.


There are currently no comments.