Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dart how to make a function that can accept any number of args

Tags:

dart

Coming from python, i know i can easily accomplish that :

def someFunc(*args):
    for i in args:
        print i

That way i can give 100 args with ease.

How to do something like that on Dart ?

Thx.

like image 724
Faris Nasution Avatar asked Apr 28 '13 11:04

Faris Nasution


People also ask

How do you make a function accept any number of arguments?

So if you'd like to make a function that accepts any number of positional arguments, use the * operator.

How many arguments can a function receive?

Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma.

How many ways you can pass the parameters in Dart?

Dart has three ways to declare parameters for a function. Required positional parameters. Named parameters. Optional positional parameters.


2 Answers

There is no real vararg support in Dart. There was, but it has been removed. As Fox32 said, you can do this with noSuchMethod. But, if there is no real need to call the method like method(param1, param2, param3), you could just skip this step and define a Map or List as parameter. Dart supports literals for both types, so the syntax is also short and clear:

void method1(List params) {
  params.forEach((value) => print(value));
}

void method2(Map params) {
  params.forEach((key, value) => print("$key -- $value"));
}

void main() {
  method1(["hello", "world", 123]);
  method2({"name":"John","someNumber":4711});
}
like image 77
MarioP Avatar answered Oct 16 '22 17:10

MarioP


You can use the noSuchMethod method on a class (Probably in combination with the call() method, but i haven't tried that). But it seems like you loose some checking features of the dart editor when using this (at least for me).

The method has a Invocation instance as a parameter that contains the method name and all unnamed parameters as a list and all named parameters as a hashmap.

See here for more details about noSuchMethod and call(). But the link contains outdated informations that do not apply for Milestone 4, see here for the changes.

Something like this:

typedef dynamic FunctionWithArguments(List<dynamic> positionalArguments, Map<Symbol, dynamic> namedArguments);

class MyFunction
{
  final FunctionWithArguments function;

  MyFunction(this.function);

  dynamic noSuchMethod(Invocation invocation) {
    if(invocation.isMethod && invocation.memberName == const Symbol('call')) {
      return function(invocation.positionalArguments, invocation.namedArguments);
    }

    return;
  }
}

Usage:

class AClass {
  final aMethod = new MyFunction((p, n) {
    for(var a in p) {
      print(a);
    }
  });
}


var b = new AClass();

b.aMethod(12, 324, 324);
like image 35
Fox32 Avatar answered Oct 16 '22 18:10

Fox32