How to overcome error message "java: pattern matching in instanceof is not supported in -source 8"?

691 Views Asked by At

code

package org.example;

public class PatternSample {

    static String formatter(Object o) {
        String formatted = "unknown";
        if (o instanceof Integer i) {
            formatted = String.format("int %d", i);
        } else if (o instanceof Long l) {
            formatted = String.format("long %d", l);
        } else if (o instanceof Double d) {
            formatted = String.format("double %f", d);
        } else if (o instanceof String s) {
            formatted = String.format("String %s", s);
        }
        return formatted;
    }

    public static void main(String[] args) {
        System.out.println(formatter("3.33"));
    }

}

error message

java: pattern matching in instanceof is not supported in -source 8

enter image description here

1

There are 1 best solutions below

1
On

I don't think you need to change to Java 16 in this particular case, although it's certainly an option to do so.

String.format actually takes Object arguments after the pattern, so you don't need to cast o to the various different types, which is what the "extended instanceof" actually does. Just remove identifiers from the instanceof checks, and pass o as the argument to each call to format. So you'll have something like this.

    if (o instanceof Integer) {
        formatted = String.format("int %d", o);
    } else if (o instanceof Long) {
        formatted = String.format("long %d", o);
    } else if (o instanceof Double) {
        formatted = String.format("double %f", o);
    } else if (o instanceof String) {
        formatted = String.format("String %s", o);
    }