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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With