Skip to content

Final variable type promotion is lost inside a closure if followed by try/catch #46532

Closed
@renatoathaydes

Description

@renatoathaydes
  • Dart SDK Version (dart --version)
Dart SDK version: 2.13.4 (stable) (Wed Jun 23 13:08:41 2021 +0200) on "macos_x64"

Description

The following code attempts to use type promotion of a final variable, which should be guaranteed to work in this case because the variable in question is final.

mixin A {
}

class Foo with A {
  final foo = 'foo';
}

class Bar with A {
  final bar = 'bar';
}

void main() {
  final A a;
  try {
    a = Foo();
  } catch (e) {
    print('ERROR: $e');
    return;
  }
  if (a is Foo) {
    print(['foo', 'bar'].firstWhere((i) => i == a.foo)); // fails to compile
  } else if (a is Bar) {
    print(['foo', 'bar'].firstWhere((i) => i == a.bar)); // fails to compile
  }
}

The two lines where it says // fails to compile fail because of the errors (from DartPad):

Error: The getter 'foo' isn't defined for the class 'A'.
 - 'A' is from 'package:dartpad_sample/main.dart' ('lib/main.dart').
    print(['foo', 'bar'].firstWhere((i) => i == a.foo));
                                                  ^^^
lib/main.dart:23:51:
Error: The getter 'bar' isn't defined for the class 'A'.
 - 'A' is from 'package:dartpad_sample/main.dart' ('lib/main.dart').
    print(['foo', 'bar'].firstWhere((i) => i == a.bar));
                                                  ^^^
Error: Compilation failed.

I am almost certain this is a bug because changing the code that assigns a from:

  final A a;
  try {
    a = Foo();
  } on FormatException catch (e) {
    print('ERROR: $e');
    return;
  }

to:

final A a = Foo();

... causes the problem to go away. But at the point where the error occurs, it shouldn't matter which of the two above was used, as a is guaranteed to be assigned and final after this.

This issue might be related to issue 32285?

Metadata

Metadata

Assignees

No one assigned

    Labels

    closed-duplicateClosed in favor of an existing report

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions