I try to set default value in function:
bool isOnGoing([DateTime date = DateTime.now()]) {
...
}
But studio returns "Default values of an optional parameter must be constant".
How can I set default parameter in this case?
Default values indicate that the function argument will take that value if no argument value is passed during the function call. The default value is assigned by using the assignment(=) operator of the form keywordname=value.
Default parameter in Javascript The default parameter is a way to set default values for function parameters a value is no passed in (ie. it is undefined ). In a function, Ii a parameter is not provided, then its value becomes undefined . In this case, the default value that we specify is applied by the compiler.
Default function parameters allow formal parameters to be initialized with default values if no value or undefined is passed. function foo(a, b) { a = typeof a !==
The syntax you use is correct, but as the error message says, the value has to be a compile time constant.
A compile time constant doesn't make sense for DateTime.now()
.
As a workaround, you can use:
/// Returns `true` is still going on.
///
/// [date] the date to check.
/// as default value `DateTime.now()` is used
/// if no value or `null` was passed.
bool isOnGoing([DateTime date]) {
date ??= DateTime.now();
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With