我有一个通用的静态方法,如下所示:
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
是什么?
答案 0 :(得分:4)
关于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
typedef,它引用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