Reputation: 4060
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?
Upvotes: 12
Views: 5706
Reputation: 71693
Edit: Yes, now you can. Dart 3.0 introduced pattern matching, so now you can write:
switch (currentState) {
case classA():
//do stuff
case classB():
//do stuff
case classC():
//do stuff
}
You can also do much more, read about it here: https://dart.dev/language/patterns
The historical answer was:
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 usingidentical
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.
Upvotes: 10
Reputation: 768
switch (runtimeType) {
case ClassA: //do stuff
return;
case ClassB: //do stuff
return;
}
Upvotes: 6
Reputation: 1752
You can't use the same syntax as in Kotlin but you can use Freezed.
https://pub.dev/packages/freezed
It allows you to use a similar syntax.
Considering this model:
@freezed
abstract class Model with _$Model {
factory Model.first(String a) = First;
factory Model.second(int b, bool c) = Second;
}
You can use when in the following way:
var model = Model.first('42');
print(
model.when(
first: (String a) => 'first $a',
second: (int b, bool c) => 'second $b $c'
),
); // first 42
Upvotes: 5