Consider the following code fragment:
void main(List<String> args) {
if (args.length > 0) {
fun(optionalParam: args[0]);
} else {
fun();
}
}
void fun({String optionalParam = 'magicValue'}) {
print(optionalParam);
}
In the 'main' function I might not want to know what 'magicValue' is, that's why it's a default. But if there were a bunch of other arguments involved in calling fun, I might not have such a simple if statement in 'main'.
Is there a cleaner way to write this?
I tried asking gemini about this and it suggested using a ternary operator to pass null instead, but that is clearly wrong.
This was asked earlier, and one response was basically 'use null and set the magic value internally'.
However this response was from 2013, and predates dart's null safety changes I think, so I'm curious what the idioms are for this behavior.
One possibility would be to do something like this:
void fun([String? optionalParam]) {
String _param = optionalParam ?? 'magicValue';
print(_param);
}
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1736688589a3906984.html
评论列表(0条)