Skip to content

Instantly share code, notes, and snippets.

@orllewin
Last active October 25, 2022 14:22
Show Gist options
  • Select an option

  • Save orllewin/b952eb20e6fe75cd3b322576906c5240 to your computer and use it in GitHub Desktop.

Select an option

Save orllewin/b952eb20e6fe75cd3b322576906c5240 to your computer and use it in GitHub Desktop.
alluring-lotus-3583
//Exploring basic Kotlin style _when_ syntax in Dart
void main() {
int code = 100;
var x = when(code,{
100: 1,
200: () => print("Success"),
400: () => print("Client Error"),
500: () => print("Server Error"),
(code > 400 && code < 500): () => print("Undefined client error: $code")
}, () => {print("Unknown Code")
});
print("x: $x");
}
dynamic when<T>(T condition, Map<dynamic, dynamic> branches, Function() none) {
var consumed = false;
var returnValue;
branches.forEach((key, value) {
if (key.runtimeType == condition.runtimeType && key == condition) {
if (value.runtimeType == Function) {
value.call();
consumed = true;
} else {
returnValue = value;
consumed = true;
}
} else if (key.runtimeType == bool && key as bool == true) {
value.call();
consumed = true;
}
});
if (consumed) {
return returnValue;
} else {
none.call();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment