Sdk: Unable to use "case null" in a switch statement

Created on 6 Nov 2018  路  3Comments  路  Source: dart-lang/sdk

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.

NNBD area-language core-l type-enhancement

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 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.

All 3 comments

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.

Was this page helpful?
0 / 5 - 0 ratings