Created with <3 with dartpad.dev.
Last active
October 25, 2022 14:22
-
-
Save orllewin/b952eb20e6fe75cd3b322576906c5240 to your computer and use it in GitHub Desktop.
alluring-lotus-3583
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| //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