Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dart - named parameters using a Map

Tags:

dart

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".

like image 243
Fabrizio Ettore Messina Avatar asked May 22 '13 09:05

Fabrizio Ettore Messina


1 Answers

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));
}
like image 116
Alexandre Ardhuin Avatar answered Sep 20 '22 09:09

Alexandre Ardhuin