Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use 'is' operator in a switch case in Dart?

I feel like this is a stupid question, but I cant get it to work.

What I have:

if (current is classA){
   //do stuff
   return;
}
if (current is classB){
   //do stuff
   return;
}
if (current is classC){
   //do stuff
   return;
}

What I want:

switch (currentState) {
   case is classA: { 
      //do stuff
      break;
   }
   case is classB: { 
      //do stuff
      break;
   }
   case is classC: { 
      //do stuff
      break;
   }
}

What I really want (Kotlin):

When (currentState){
   is classA -> //do stuff
   is classB -> //do stuff
   is classC -> //do stuff
}

Is there anyway I can use the Dart Switch like the Kotlins When operator, or at least use other operators then == to assert the case evaluations?

like image 591
Joel Broström Avatar asked Feb 28 '19 16:02

Joel Broström


1 Answers

No.

The Dart switch case is a very low-level construct. It allows only constant-value expressions that don't override operator == (except for a few basic platform types), so effectively it can be implemented using identical checks.

There is no ability to do complicated checks, or checks on the type of the object, only identity checks.

The recommended pretty way to do what you want is to have ClassA, ClassB and ClassC all implement an interface with a doStuff member, and then do:

 currentState.doStuff()

If that is not possible, you are back to the if sequence.

like image 90
lrn Avatar answered Sep 24 '22 21:09

lrn