最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin4浏览0评论

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);
}
发布评论

评论列表(0)

  1. 暂无评论