This may be expected, but it caught me out:
main() {
String a;
switch(a) {
case "a":
print("a");
break;
case null:
print("null");
break;
}
}
It gives the error:
Case expressions must have the same types, 'null' isn't a 'String'.
It seems strange that it says null is not a String, when it's the actual value assigned to the String variable.
This is a known consequence of the way the specification is written. The specification requires all case expressions to be instances of the same class, and null is an instance of Null, not String.
Maybe we can begin to loosen up a little, say, to all expressions just needing to be subtypes of the static type of the case expression, now that we have a non-optional type system.
Are there any plans for this change to be implemented?
For code that has not opted in to null safety, we don't intend to change the existing behavior. (You can always use a default case instead of case null as a workaround.) When opted in to null safety, it now does the expected static-type based analysis and allows case null if the value's type is nullable.
Most helpful comment
This is a known consequence of the way the specification is written. The specification requires all case expressions to be instances of the same class, and
nullis an instance ofNull, notString.Maybe we can begin to loosen up a little, say, to all expressions just needing to be subtypes of the static type of the case expression, now that we have a non-optional type system.