mercredi 22 mai 2019

How to access Switch argument inside a case in Dart

I want to switch on animals and take the appropriate action.

switch (animal.runtimeType) {
  case Cat:
    animal.pet();
    break;
  case Crocodile:
    animal.runAway();
    break;
  default:
    print('Not a known animal.');
} 

If I were if-chaining this would work, since the scope would know the type of animal in the if (animal is Cat){} block.

For some reason this is not the case with switch statements. In this case I will get the error

The method pet() isn't defined for the class animal

How can I use the case assertion in the case block? I cant use as since my CI Lint won't allow it (which is a good thing) and it makes no sense to use an If operation inside the case, since using a if-else statement would be less code and offer more usability.

Aucun commentaire:

Enregistrer un commentaire