Functions
int func(int a)
{
return 0;
}
int func(int a) => a + 1;Optional parameters
// the '?' sets a none set argument to null
String fullName(String first, String last, [String? title]) {
if (title != null) {
return '$title $first $last';
} else {
return '$first $last';
}
}Default parameters…
bool withinTolerance(int value, [int min = 0, int max = 10]) {
return min <= value && value <= max;
}
withinTolerance(9, 7, 11)
withinTolerance(9, min: 7, max: 11)
withinTolerance(min: 7, max: 11, 9)
withinTolerance(min: 7, 9, max: 11) // THIS IS SO STUPID WHY IS THIS A THING
withinTolerance(9, 7) // min is set to 7
Making Named Parameters Required
You might like to make value a named parameter as well. That way you could call the function like so:
withinTolerance(value: 9, min: 7, max: 11)
However, this brings up a problem. Named parameters are optional by default, but value can’t be optional. If it were, someone might try to use your function like this:
withinTolerance()
Should that return true or false? It doesn’t make sense to return anything if you don’t give the function a value. This is just a bug waiting to happen.
What you want is to make value required instead of optional, while still keeping it as a named parameter. You can achieve this by including value inside the curly braces and adding the required keyword in front:
bool withinTolerance({
required int value,
int min = 0,
int max = 10,
}) {
return min <= value && value <= max;
}
// when doing it like that you need to specify the params
withingTolerance(value: 10);