我可能在语法上或实际上做错了什么,所以“不要那样做”可能是有效的,但似乎这应该有效:
class Thing {
//static dynamic noop = () { }; // fails
static dynamic noop = ([dynamic value]) { }; // works for null cases
dynamic _callback;
Thing._([dynamic callback([dynamic value])])
: this._callback = callback != null ? callback : Thing.noop;
factory Thing([dynamic callback([dynamic value])]) {
return new Thing._(callback);
}
}
当我运行这些测试时,第一个失败,但第二、第三和第四次通过:
//Caught type '() => dynamic' is not a subtype of type '([dynamic]) => dynamic' of 'callback'.
test('callback with optional param', () {
var thing = new Thing(() { });
thing.doCallback();
thing.doCallback('data');
});
test('callback with optional param', () {
var thing = new Thing(([_]) { });
thing.doCallback();
thing.doCallback('data');
});
test('callback with optional param', () {
var thing = new Thing();
thing.doCallback();
thing.doCallback('data');
});
test('callback with optional param', () {
var thing = new Thing(null);
thing.doCallback();
thing.doCallback('data');
});