In dart, how can I optionally pass an optional argument? - Stack Overflow

Consider the following code fragment:void main(List<String> args) {if (args.length > 0) {fun(

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条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信