Reputation: 20223
In Javascript, one can use apply
to move arguments in bulk from one function to another? How is this done in Dart?
To use a mismatch of Dart and Javascript:
Object proxy(<any number and type of arguments>) {
if(feelGood)
return goodFunc.apply(arguments);
else
return badFunc.apply(arguments);
}
In Dart, how does one
specify any number and type of arguments?
apply the arguments from one function to another?
Upvotes: 1
Views: 321
Reputation: 71743
You can't create a function that takes any number of arguments in Dart. For that, you have to fall back on noSuchMethod. To call a function with a dynamic list of arguments, you can use Function.apply.
Example:
class _MyProxy implements Function {
const _MyProxy();
noSuchMethod(InvocationMirror m) {
if (m.memberName != #call) return super.noSuchMethod(m);
return Function.apply(feelGood ? goodFunc : badFunc, m.positionalArguments, m.namedArguments);
}
}
const Function proxy = const _MyProxy();
This class captures invalid calls using noSuchMethod. It acts as a function by intercepting the "call" method. It then works as your proxy method intends by forwarding the arguments to either goodFunc or badFunc using Function.apply.
You can then write:
proxy(<any number and type of argument>);
and have it call either goodFunc or badFunc with those exact arguments.
Upvotes: 3
Reputation: 76273
You can use Function.apply :
main() {
final l = [];
Function.apply(l.add, ['v1']);
print(l); // display "[v1]"
}
Dart does not support varargs on method but you can simulate them with noSuchMethod
(see Creating function with variable number of arguments or parameters in Dart)
Upvotes: 2