Home > front end >  Why dart type casting affects the original casted variable
Why dart type casting affects the original casted variable

Time:10-17

I am learning dart programming language version 2.14.3 and came across an odd issue that I am unable to understand.

The following code doesn't compile obviously because isEven is only defined in int class.

void main() {
  const num someNumber = 3;
  print(someNumber.isEven);
}

However, casting someNumber to int and assigning the value to a different variable, solved the problem and the code compiles with print(someNumber.isEven); not changed. The following code compiles.

void main() {
  const num someNumber = 3;
  final someInt = someNumber as int;
  print(someNumber.isEven);
}

Is this a bug in dart or a language feature that I am not aware of?

CodePudding user response:

When you do:

final someInt = someNumber as int;
print(someNumber.isEven);

If the cast fails, an uncaught TypeError will be thrown and exit your function. Therefore, the compiler can logically deduce that, if print(someNumber.isEven) is reached, someNumber must be an int. Therefore, on lines that follow the cast, the original object is promoted to the casted type. (Note that only local variables can be promoted.) Put another way, the cast acts as a type assertion; you don't need the someInt variable:

someNumber as int;
print(someNumber.isEven);

This is the same principle by which ! (which is basically a non-null cast operator) can promote a local nullable variable to be non-nullable and avoid the need to pepper ! for subsequent accesses to the same variable.

  •  Tags:  
  • dart
  • Related