Type test patterns: allow expression type to match pattern type

Anthony Vanelverdinghe dev at anthonyv.be
Sun Apr 4 17:16:44 UTC 2021


When using a type test pattern, the compiler gives an error if the expression type is a subtype of the pattern type.
While I agree that it doesn't make sense for the expression type to be a strict subtype, I believe it should be allowed to be the same type.

For example, with a `NavigableMap<String, String> map`, instead of writing:
if(map.higherKey("foo") != null) {
    Files.writeString(path, map.higherKey("foo"));
}

We could write:
if(map.higherKey("foo") instanceof String kNext) {
    Files.writeString(path, kNext);
}

Or, with a `BufferedReader in`, instead of writing:
String line;
while((line = in.readLine()) != null) { ... }

We could write:
while(in.readLine() instanceof String line) { ... }

Has this idea been considered before? If so, why was it turned down? If not, shall I file an RFE for this?

Kind regards,
Anthony



More information about the amber-dev mailing list