代码之家  ›  专栏  ›  技术社区  ›  arielnmz

如何定义泛型函数的typedef?

  •  3
  • arielnmz  · 技术社区  · 7 年前

    我有一个像这样的通用静态方法:

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

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

    The return type '(GenericClass<K>) → MyClass<K>' isn't a '(GenericClass<dynamic>) → MyClass<dynamic>', as defined by the method 'build'.

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

    The return type '(GenericClass<K>) → MyClass<K>' isn't a '<K>(GenericClass<K>) → MyClass<K>', 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

    1 回复  |  直到 7 年前
        1
  •  4
  •   Nate Bosch    7 年前

    T 以下内容:

    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 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
    
    推荐文章