Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to conditionally cast a type in dart?

Tags:

casting

dart

It seems if it's just a variable, I can conditionally cast like this.

Animal animal = Dog();
if (animal is Dog) {
  animal.bark(); // animal is of type Dog here
}

But if it's a property on a class, how do I conditionally cast?

House house = House()
house.animal = Dog();
if (house.animal is Dog) {
  house.animal.bark(); // fail
}

I know I can do it like this

if (house.animal is Dog) {
  Dog animal = house.animal;
  animal.bark();
}

But that seems cumbersome. Is there anyway I can check and cast type in one go like I can with variables?

Thanks a lot.

like image 330
hgl Avatar asked May 28 '19 01:05

hgl


1 Answers

This is a Dart limitation. You can check the reason in this issue (thanks, jamesdlin).

Instantiating the Animal subclass inside each if block can be cumbersome, in case you have lots of conditions.

I would do, instead:

final house = House()..animal = Dog();
final animal = house.animal;

if (animal is Dog) {
  animal.bark();
} else if (animal is Cat) {
  animal.meow();
} else if (animal is Wolf) {
  animal.howl();
}
like image 176
Hugo Passos Avatar answered Oct 21 '22 01:10

Hugo Passos