How to use Pattern Matching for instanceof operator in Java?

Let’s say you have a generic method which accepts any object as a parameter.

Based on the type of the object , the method performs custom operations.

Traditionally to implement this you need to do the following steps:

  1. Check the passed parameter using instanceof operator for the specific type
  2. If it matches , cast the passed parameter to the specific type and assign it to a variable.
  3. Perform the custom operation on the new variable

Using pattern matching for instance of , you can get rid of the second step.

Let’s check it using an example.

Lets create a generic method add() which takes a single parameter.

If it is an integer it adds the number to itself and returns it.

If it is a string it concatenates the value to itself and return it.

Here is the code written in the traditional way:

Object add(Object obj) {
 
       if (obj instanceof Integer) {
 
           Integer value = (Integer) obj;
 
           return value + value;
       }
 
       if (obj instanceof String) {
 
           String value = (String) obj;
 
           return value + value;
       }
       return null;
 
   }

You can refactor the above code using pattern matching like this:

Object addWithPatternMatching(Object obj) {
 
        if (obj instanceof Integer value) {
 
            return value + value;
        }
 
        if (obj instanceof String value) {
 
            return value + value;
        }
        return null;
 
    }

Both return the same output but the latter has less lines of code.

In the latter case , the variable to be cast is immediately declared next to the instanceof check of the parameter passed. It is then used within the scope.

Pattern matching for instanceof feature has now became a permanent feature of Java with the release of Java 16.


Posted

in

by

Comments

Leave a Reply

Discover more from The Full Stack Developer

Subscribe now to keep reading and get access to the full archive.

Continue reading