if (o instanceof String s) {
var foo = s.indexOf("bar");
}
Java 17 introduced a preview of the same feature for switch statements return switch (o) {
case Integer i -> String.format("int %d", i);
case Long l -> String.format("long %d", l);
case Double d -> String.format("double %f", d);
case String s -> String.format("String %s", s);
default -> o.toString();
};
Future versions will have improved support: http://openjdk.java.net/jeps/420)