Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a collection of arguments passed to a Dart function/constructor call

Tags:

dart

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

Is this possible in Dart?

like image 416
computmaxer Avatar asked May 28 '15 06:05

computmaxer


1 Answers

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.

like image 158
Alexandre Ardhuin Avatar answered Oct 30 '22 03:10

Alexandre Ardhuin