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
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 takesObject
arguments after the pattern, so you don't need to casto
to the various different types, which is what the "extendedinstanceof
" actually does. Just remove identifiers from theinstanceof
checks, and passo
as the argument to each call toformat
. So you'll have something like this.