2

I am working with dart without allowing implicit dynamics and casts and I noticed the following:

When working with a local variable, I can use a type check on that variable and if the test passes, the compiler will just assume that I can use that variable as that type:

var emp; // set to something
if (emp is Person) {
  // The compiler infers that emp is a person within this scope
  // so it allows me to use Person's member functions and variables
  // without the need for explicit typecast
  // https://dart.dev/guides/language/language-tour#type-test-operators
  emp.firstName = 'Bob';
}

However, this does not work if the variable is the member variable of an object:

class SuperPerson {
  Object _emp;

  /* Various things that could be doing things with _emp here */

  void memberFun() {
    if (_emp is Person) {
      _emp.firstName = 'Bob'; // ERROR: The setter firstName is not defined for type Object.
      (_emp as Person).firstName = 'Bob'; // workaround but would like to avoid casts that could fail.
    }
  }
}

Why is that and how can I overcome it? Could it be because of potentially other threads changing the value of _emp in between the test and the use?

namesis
  • 157
  • 10

1 Answers1

2

Edit: I had forgotten that I had already answered this question. See that one instead.

(Since this answer had already been accepted at the time of this edit, I cannot delete it.)

jamesdlin
  • 81,374
  • 13
  • 159
  • 204