Last active
May 6, 2024 15:52
-
-
Save ElanDeyan/79ec558b64faf0510bcee2d78501b33e to your computer and use it in GitHub Desktop.
Dart read-only function parameters.
This file contains 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() { | |
const two = 2; | |
const ten = 10; | |
var aNumber = ten; | |
print('aNumber before pureAdd: $aNumber'); | |
print(pureAdd(aNumber, two)); | |
print('aNumber after pureAdd: $aNumber'); | |
print('aNumber before impureAdd: $aNumber'); | |
print(impureAdd(aNumber, two)); // why 102? something is wrong inside the impureAdd | |
print('aNumber after impureAdd: $aNumber'); // but outside the function everything still fine | |
} | |
// Use the final modifier to make your parameters read-only inside function's scope | |
int pureAdd(final int a, final int b) { | |
// a = 100; // uncomment this line and you will got an error | |
return a + b; | |
} | |
int impureAdd(int a, int b) { | |
a = 100; // oops! | |
return a + b; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment