Last active
January 9, 2022 17:23
-
-
Save kranfix/d22b7bee770ad016e41e75b6d3c3c3e5 to your computer and use it in GitHub Desktop.
Solution to var problem using a closure in Dart
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
void main() { | |
final list = <int>[1, 2, 3, 4, 2, -1, 5]; | |
final maxValue = 12; | |
final sum = (){ | |
var sum = 0; | |
for(final val in list) { | |
sum += val; | |
} | |
if(sum > maxValue) { | |
sum = maxValue; | |
} | |
return sum; | |
}(); // See the parenthesis to execute the closure/function | |
/// ... more code that uses `sum` ... | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment