0

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

Vy Do
  • 46,709
  • 59
  • 215
  • 313
  • 4
    The feature was released in Java [16](https://openjdk.org/jeps/394) and should work in Java [18](https://docs.oracle.com/en/java/javase/18/language/pattern-matching-instanceof-operator.html). As per the error message are you sure that your project is configured for Java 16 source or newer, the error message suggests its setup for Java 8 source. Also related: [Pattern matching instanceof](https://stackoverflow.com/questions/61939967/pattern-matching-instanceof) – sorifiend Jul 20 '22 at 03:33

1 Answers1

2

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);
    }
Dawood ibn Kareem
  • 77,785
  • 15
  • 98
  • 110
  • 2
    In fact, it isn’t even necessary to use an expensive `String.format` call. A plain `String formatted = o instanceof Integer? "int " + o: o instanceof Long? "long " + o: o instanceof Double? "double " + o: o instanceof String? "String " + o: "unknown";` would do. No need to know whether to use `%d`, `%f`, or `%s` here (not that it matters much, as `%s` would do for all of them anyway). – Holger Jul 20 '22 at 11:17