Skip to content

Analyzer does not infer type of dynamic class fields after typecheck #27813

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
lassedamgaard opened this issue Nov 14, 2016 · 1 comment
Closed

Comments

@lassedamgaard
Copy link

For function scoped dynamic variables the type is inferred inside a block that checks the type. For example

if (dynamicVar is String) {
  // dynamicVar is inferred to be String
}

However this doesn't work for class fields as in the following example:

class Test  {
  dynamic classVariable;
  List<String> stringList;

  void checkClassVariable() {
    if (classVariable is String) {
      // ERROR: Could not infer type parameter E, dynamic must be of type String. ([untitled1] bin/main.dart:7)
      stringList = [classVariable];
    }
  }

  void checkMethodVariable() {
    dynamic methodVariable;
    if (methodVariable is String) {
     // Type is inferred 
      stringList = [methodVariable];
    }
  }
}
@eernstg
Copy link
Member

eernstg commented Nov 14, 2016

This works as designed.

The feature is called type promotion in the language specification, and it is specified to apply to local variables and function/method parameters, but not instance variables, static variables, nor library variables (aka global variables).

The reason why this feature does not generalize to those "more global" kinds of variables is that it is based on an analysis which ensures that the given variable keeps the same value between the type test and the usage. Since arbitrary code can access those "more global" variables (including instance variables, if the enclosing object is accessible), it is much more complex (and in general it is an undecidable question) whether the variable is mutated between those two points in time. So the language avoids diving into that tar pit.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants