Last active
July 6, 2018 20:37
-
-
Save aab29/29bce9ad7fdc57de65d802bf493f0346 to your computer and use it in GitHub Desktop.
Showing off Dart's two syntaxes for optional arguments: optional named arguments and optional positional arguments.
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
| enum SheepSoundLength { | |
| short, | |
| medium, | |
| long | |
| } | |
| const LettersCountBySheepSoundLength = const { | |
| SheepSoundLength.short : 1, | |
| SheepSoundLength.medium : 3, | |
| SheepSoundLength.long : 6 | |
| }; | |
| void makeSheepSounds(int soundsCount, [SheepSoundLength soundLength = SheepSoundLength.medium]) { | |
| var sounds = []; | |
| for (var soundIndex = 0; soundIndex < soundsCount; soundIndex++) { | |
| var lettersCount = LettersCountBySheepSoundLength[soundLength]; | |
| sounds.add("B${"a" * lettersCount}h"); | |
| } | |
| print(sounds.join(" ")); | |
| } | |
| void makeDuckSounds(int soundsCount, {int soundLength = 3, bool loud = false}) { | |
| var sounds = []; | |
| for (var soundIndex = 0; soundIndex < soundsCount; soundIndex++) { | |
| var sound = "Qu${"a" * soundLength}ck"; | |
| if (loud) { | |
| sound = sound.toUpperCase(); | |
| } | |
| sounds.add(sound); | |
| } | |
| print(sounds.join(" ")); | |
| } | |
| void main() { | |
| // Calling with no optional positional arguments. | |
| makeSheepSounds(3); | |
| // Calling with the optional positional argument. | |
| makeSheepSounds(7, SheepSoundLength.short); | |
| // Calling with no optional named arguments. | |
| makeDuckSounds(5); | |
| // Calling with both optional named arguments. | |
| makeDuckSounds(2, soundLength: 1, loud: false); | |
| // Optional named arguments can be listed in any order! | |
| makeDuckSounds(1, loud: true, soundLength: 20); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment