Dart - named parameters using a Map

I would like to know if I can call a function with name parameters using a map e.g.

void main()
{
  Map a = {'m':'done'}; // Map with EXACTLY the same keys as slave named param.
  slave(a);
}
void slave({String m:'not done'}) //Here I should have some type control
{ 
  print(m); //should print done
}

the hack here is to not use kwargs but a Map or, if you care about types, some interfaced class (just like Json-obj), but wouldn't be more elegant to just have it accept map as kwars? More, using this hack, optional kwargs would probably become a pain... IMHO a possible implementation, if it does not exist yet, would be something like:

slave(kwargs = a)

e.g. Every function that accepts named param could silently accept a (Map) kwargs (or some other name) argument, if defined dart should, under the hood, take care of this logic: if the key in the Map are exactly the non optional ones, plus some of the optional ones, defined in the {} brackets, and of compatible types "go on".

Upvotes: 20

Views: 12488

Answers (2)

aym
aym

Reputation: 175

The answer of @alexandre-ardhuin is correct but is missing something : How to call a constructor as Function. You have to use the property new after the Classname. Here's an example :

main() {
  final a =  new Map<Symbol, dynamic>();
  Function.apply(MyClass.new, [], a);
}

Upvotes: 3

Alexandre Ardhuin
Alexandre Ardhuin

Reputation: 76283

You can use Function.apply to do something similar :

main() {
  final a = new Map<Symbol, dynamic>();
  a[const Symbol('m')] = 'done';
  Function.apply(slave, [], a);
}

You can also extract an helper method to simplify the code :

main() {
  final a = symbolizeKeys({'m':'done'});
  Function.apply(slave, [], a);
}

Map<Symbol, dynamic> symbolizeKeys(Map<String, dynamic> map){
  return map.map((k, v) => MapEntry(Symbol(k), v));
}

Upvotes: 25

Related Questions