简体   繁体   中英

Dart - named parameters using a Map

I would like to know if I can call a function with name parameters using a map eg

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)

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

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));
}

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM