skip to Main Content
class A {
  int b;
  int c;

  A(this.b, this.c);
}

void testFunc(Object param) {
  print((param as A).b);
  print(param.c); //is there documentation somewhere? Why is there no need type casting?
}

Why is there at second time no need type casting? I need ref to documentation.

2

Answers


  1. Dart is smart

    Dart analyzer logically decides which type this object is, generally this cast expression has 2 possible scenarios:

    (param as A)
    
    • Successful cast which means param is an instance of A class or a subtype of it.

    in this case all coming code in this block of code will treat param
    as an instance of A just like if you are just checking the type:

    if(param is A){
     // this scope (if body) will treat param as an instance of A 
     }
    
    • Wrong cast which generates a TypeError

    TypeError causes the program to crash, as you know (error shouldn’t be caught because they represent unexpected program flow).

    So, you will get an error that indicates that param is not of type A, say you caught that error : the next expression of param.c will cause an error indicating that param doesn’t have a getter called c.

    after all, the successful cast scenario most likely to answer your question.

    Login or Signup to reply.
  2. The Dart code analyzer remembers the type for a local variable (such as your param). Since the first line in testFunc already makes it clear that param is an A rather than just an Object, it knows that for the rest of the function too.

    Note that this applies only to local variables and parameters, as more global value might actually change between lines.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search