Dart-使用地图命名的参数 [英] Dart - named parameters using a Map

查看:63
本文介绍了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
}

这里的技巧是不使用kwargs,而是使用Map或者,如果您关心类型,那么可以使用一些接口类(就像Json-obj一样),但是让它接受map作为kwars不会更优雅吗?
此外,使用此hack,可选的kwarg可能会很痛苦...
恕我直言,可能的实现方式(如果尚不存在)将是:

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)

例如每个接受命名参数的函数都可以静默地接受一个(Map)kwargs(或其他名称)参数,如果定义了dart,则应在后台执行此逻辑:如果Map中的键正好是非可选键,加上在{}括号中定义的一些可选类型,以及兼容类型为继续。

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

推荐答案

使用 Function.apply 做类似的事情:

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){
  final result = new Map<Symbol, dynamic>();
  map.forEach((String k,v) { result[new Symbol(k)] = v; });
  return result;
}

这篇关于Dart-使用地图命名的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆