Skip to content

Instantly share code, notes, and snippets.

@aab29
Last active July 6, 2018 20:37
Show Gist options
  • Select an option

  • Save aab29/29bce9ad7fdc57de65d802bf493f0346 to your computer and use it in GitHub Desktop.

Select an option

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.
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