Skip to content

if case with type check turns values to null if not covered in the first if case and the assigned name is the same as the local variable #59613

@denniskaselow

Description

@denniskaselow

This code:

void main() {
  for (final thing in [42.42, 'foo', Object()]) {
    if (thing case final double thing) {
      print('$thing is double');
    } else if (thing case final String thing) {
      print('$thing is String');
    } else if (thing case final Object thing) {
      print('$thing is Object');
    } else  {
      // analyzer warns this is dead code, but it gets executed because thing is null
      print('$thing is unknown ${thing.runtimeType}');
    }
    // accessing thing here is still the original value
  }
}

Outputs:

42.42 is double
null is unknown Null
null is unknown Null

Expected output:

42.42 is double
foo is String
Instance of 'Object' is Object

The output is correct if I don't assign the loop variable to a variable with the same name in the if case.

A loop isn't required for this bug, something like final thing = ['foo', 1].first; has the same problem.

Simply using final thing = 'foo'; before the if case is even worse:

DartPad caught unhandled JSNoSuchMethodError:
TypeError: can't access property Symbol("dartx.runtimeType"), thing is null
unparsed                                                                  TypeError: can't access property Symbol("dartx.runtimeType"), thing is null
blob:null/893fe534-725f-4a0f-a513-3941f5589dd5 444:18                     load__dartpad_main.<fn>.<fn>
https://storage.googleapis.com/nnbd_artifacts/3.5.4/dart_sdk.js 48513:14  _rootRun
https://storage.googleapis.com/nnbd_artifacts/3.5.4/dart_sdk.js 47560:14  run
https://storage.googleapis.com/nnbd_artifacts/3.5.4/dart_sdk.js 48660:92  _runZoned
https://storage.googleapis.com/nnbd_artifacts/3.5.4/dart_sdk.js 48618:18  runZoned
blob:null/893fe534-725f-4a0f-a513-3941f5589dd5 442:20                     capture
Stack trace truncated and adjusted by DartPad...

Tested on DartPad, stable and main:
Dart SDK 3.5.4 and Flutter SDK 3.24.5
Dart SDK 3.7.0-183.0.dev and Flutter SDK 3.27.0-1.0.pre.623

Metadata

Metadata

Assignees

Labels

cfe-dysfunctionalitiesIssues for the CFE not behaving as intendedlegacy-area-front-endLegacy: Use area-dart-model instead.type-bugIncorrect behavior (everything from a crash to more subtle misbehavior)

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions