Faris Nasution
Faris Nasution

Reputation: 3610

Dart coding styles

Maybe this is not a Dart specific question.

I have :

class A {
  int a;

  A(this.a);
}

class B extends A {
  String b;

  B(a, this.b) : super(a);
}

So you see, class A has an attribute int a and B just extends A and has an extra attribute String b and a wrapper class C :

class C {
  A c;

  C(this.c);

  void doSomething() {
    if (c is B) {
      print(c.b);
    } else {
      print(c.a);      
    }
  }

}

The Dart Editor complaints that the c doesn't have a getter b. How do you deal with this? I want to get rid the warning, but I don't want to add attribute b to class A

Upvotes: 1

Views: 155

Answers (3)

Alexandre Ardhuin
Alexandre Ardhuin

Reputation: 76223

The analyzer shouldn't add a warning here. I think it's related to this issue : Analyzer fails to respect certain "is" checks.

In the meanwhile, you can use (c as B).b to cast c in B.

Upvotes: 2

Florian Loitsch
Florian Loitsch

Reputation: 8128

(c as B) works, but will do a dynamic type check (which will probably be eliminated by the VM).

If you just want to remove the warning, without changing the semantics of the program you can assign to a temporary variable of the correct type:

void doSomething() {
  if (c is B) {
    B b = c;
    print(b.b);
  } else {
    print(c.a);
  }
}

Upvotes: 2

mezoni
mezoni

Reputation: 11210

You can cast expression.

print((c as B).b);

Upvotes: 1

Related Questions