6

I'm essentially looking for the JavaScript arguments functionality but in Dart.

Is this possible in Dart?

Community
  • 1
  • 1
computmaxer
  • 1,677
  • 17
  • 28

1 Answers1

7

You have to play with noSuchMethod to do that (see Creating function with variable number of arguments or parameters in Dart)

Either at the class level:

class A {
  noSuchMethod(Invocation i) {
    if (i.isMethod && i.memberName == #myMethod){
      print(i.positionalArguments);
    }
  }
}

main() {
  var a = new A();
  a.myMethod(1, 2, 3);  // no completion and a warning
}

Or at field level :

typedef dynamic OnCall(List l);

class VarargsFunction extends Function {
  OnCall _onCall;

  VarargsFunction(this._onCall);

  call() => _onCall([]);

  noSuchMethod(Invocation invocation) {
    final arguments = invocation.positionalArguments;
    return _onCall(arguments);
  }
}

class A {
  final myMethod = new VarargsFunction((arguments) => print(arguments));
}

main() {
  var a = new A();
  a.myMethod(1, 2, 3);
}

The second option allows to have code completion for myMethod and avoid a warning.

Community
  • 1
  • 1
Alexandre Ardhuin
  • 71,959
  • 15
  • 151
  • 132