On Dart 1.0.0, I just tried:

class MyClass {
    int x;
    bool b;

    MyClass(int x, [bool b = true]) {
        if(?b) {
            // ...
        }
    }
}

And am getting a compiler error on the ?b part:

The argument definition test ('?' operator) has been deprecated

So what's the "new" way of testing for whether or not an argument was supplied?

有帮助吗?

解决方案

There is no way to test if an argument was provided or not. The main-reason for its removal was, that it was very complex to forward calls this way.

The generally preferred way is to use null as "not given". This doesn't always work (for example if null is a valid value), and won't catch bad arguments. If null is used, then the parameter must not have a default-value. Otherwise the parameter is not null but takes the default-value:

foo([x = true, y]) => print("$x, $y");
foo();  // prints "true, null"

So in your case you should probably do:

class MyClass {
  int x;
  bool b;

  MyClass(int x, [bool b]) {
    if(b == null) {  // treat as if not given.
        // ...
    }
  }
}

This makes new MyClass(5, null) and new MyClass(5) identical. If you really need to catch the first case, you have to work around the type-system:

class _Sentinel { const _Sentinel(); }
...
  MyClass(int x, [b = const _Sentinel()]) {
    if (b == const _Sentinel()) b = true;
    ...
  }

This way you can check if an argument has been provided. In return you lose the type on b.

其他提示

The argument definition test operator was deprecated because it was redundant with checking for null; an optional parameter that was omitted would get the value null, and the caller could've passed null explicitly anyway. So instead use == null:

class MyClass {
    int x;
    bool b;

    MyClass(int x, [bool b]) {
        if (b == null) {
            // throw exception or assign default value for b
        }
    }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top