【问题标题】:Dart: Storing arguments in a variable before passingDart:在传递之前将参数存储在变量中
【发布时间】:2021-07-20 01:40:02
【问题描述】:

出于测试目的,能够在执行之前为函数“准备”参数是很有用的,这样可以根据任何结果检查参数。

在 JavaScript 中我可以这样做:

function testFunc ({id, count}) {
  /* perform some operation */
  return {id, count}
}

const args = {
  id: 'someId',
  count: Math.round(Math.random() * 10),
}

const res = testFunc({...args})

/* check that count is correct etc */

如何在 Dart 中实现同样的灵活性?

Map<String, dynamic> testFunc({String id, int count}) {
  /* perform some operation */
  return {
    'id': id,
    'count': count,
  };
}

final args = /* erm? */

testFunc(args); /* hmmm? */

我是否试图突破强类型语言的极限?

【问题讨论】:

    标签: flutter dart parameters parameter-passing


    【解决方案1】:

    Dart 是一种静态检查语言。 使用具有未知运行时结构(如映射)的值作为参数,无法静态检查参数的有效性。

    举个例子:

    var data = {#name: "hello", #age: 18}; 
    Person(...data)
    

    (使用符号引用源名称,与Function.applynoSuchMethod相同)。

    这里看起来很容易看到映射实际上有一个#name 和一个#age 条目,但这是因为映射是在应用程序旁边写成文字的。这是您实际上不需要传播参数的一种情况,因为您可以直接编写参数。

    在所有实际有用的情况下,不可能静态地查看映射具有哪些条目,以及每个键的值是哪些类型。地图类型Map&lt;Symbol, dynamic&gt; 不够强大,无法检查调用。你应该只使用Function.apply(Person, [], data) ... 除了我们(仍然)不允许构造函数作为函数(#216)。

    如果 Dart 已经输入了结构体/命名元组,那么可能会这样做:

    // Static type is the named tuple type `(String name, int age)`
    var data = (name: "name", age: 18);
    var person = Person(...data);
    

    此时,data 的静态类型已经足够具体,可以静态检查调用。

    这也是 GitHub 中的 issue,我从中得到了答案

    【讨论】:

      猜你喜欢
      • 2012-08-02
      • 2014-04-26
      • 1970-01-01
      • 2012-12-01
      • 2015-12-20
      • 1970-01-01
      • 1970-01-01
      • 2014-09-19
      • 1970-01-01
      相关资源
      最近更新 更多