1

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?

nbro
  • 15,395
  • 32
  • 113
  • 196
cc young
  • 18,939
  • 31
  • 90
  • 148

2 Answers2

3

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.

lrn
  • 64,680
  • 7
  • 105
  • 121
2

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)

Community
  • 1
  • 1
Alexandre Ardhuin
  • 71,959
  • 15
  • 151
  • 132
  • good going - but does seem an awfully round about solution to a pretty simple problem. I vote for Dart having "..." in the arguments and let the programmer deal with it. – cc young Nov 22 '13 at 08:44