【问题标题】:How to typedef a generic function?如何对泛型函数进行类型定义?
【发布时间】:2018-12-08 01:49:11
【问题描述】:

我有一个如下所示的通用静态方法:

static build<K>() {
    return (GenericClass<K> param) => MyClass<K>(param);
}

到目前为止我已经尝试过:

typedef F = MyClass<K> Function(GenericClass<K> param);

但它说:

The return type '(GenericClass&lt;K&gt;) → MyClass&lt;K&gt;' isn't a '(GenericClass&lt;dynamic&gt;) → MyClass&lt;dynamic&gt;', as defined by the method 'build'.

typedef F = SimpleViewModel<K> Function<k>(Store<K> param);

上面写着:

The return type '(GenericClass&lt;K&gt;) → MyClass&lt;K&gt;' isn't a '&lt;K&gt;(GenericClass&lt;K&gt;) → MyClass&lt;K&gt;', as defined by the method 'build'.

MyClass 看起来像这样:

class MyClass<T> {
  final GenericClass<T> param;

  MyClass(this.param);


  static build<K>() {
      return (GenericClass<K> param) => MyClass<K>(param);
  }
}

那么,什么是有效的typedef

【问题讨论】:

  • 我可能听起来很愚蠢,但这样做 typedef F&lt;I&gt; = MyClass&lt;I&gt; Function(GenericClass&lt;I&gt; param);static F&lt;K&gt; build&lt;K&gt;() {...} 对我来说很有意义,但我仍然无法解释原因。

标签: dart dart-2


【解决方案1】:

当涉及到 typedef 时,有两个“泛型”概念。 typedef 可以是一个类型的泛型,或者 typedef 可以引用一个泛型函数(或两者兼有):

T 上通用的 typedef:

typedef F<T> = T Function(T);

然后在使用中:

F first = (dynamic arg) => arg; // F means F<dynamic>
F<String> second = (String arg) => arg; // F<String> means both T must be String

引用M 上的泛型函数的 typedef:

typedef F = M Function<M>(M);

然后在使用中:

F first = <M>(M arg) => arg; // The anonymous function is defined as generic
// F<String> -> Illegal, F has no generic argument
// F second = (String arg) => arg -> Illegal, the anonymous function is not generic

或两者兼有:

typedef F<T> = M Function<M>(T,M);

在使用中:

F first = <M>(dynamic arg1, M arg2) => arg2; // F means F<dynamic> so the T must be dynamic
F<String second = <M>(String arg1, M arg2) => arg2; // The T must be String, the function must still be generic on the second arg and return type

【讨论】:

  • 你能解释一下为什么这不起作用吗? typedef F&lt;T&gt; = M Function&lt;M&gt;(T); F&lt;String&gt; first = &lt;int&gt;(String arg){ return arg.length; };
  • 看起来你可能想要typedef F&lt;T, M&gt; = M Function(T); F&lt;String, int&gt; first = (arg) { return arg.length; };。在您的示例中,您有两种类型的泛型, tyepdef 是泛型的,它指的是泛型函数。您的具体函数不是通用的,它只能返回int,在使用过程中不能专门返回不同的类型。
  • 是的,谢谢。错误消息有些不清楚 :-) “返回类型 'int' 不是 'int',由匿名闭包定义”
猜你喜欢
  • 1970-01-01
  • 2018-12-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-11
  • 1970-01-01
  • 2020-12-27
  • 2019-07-21
相关资源
最近更新 更多