我有一个通用的静态方法,如下所示:
static build<K>() {
return (GenericClass<K> param) => MyClass<K>(param);
}
Run Code Online (Sandbox Code Playgroud)
到目前为止,我已经尝试过:
typedef F = MyClass<K> Function(GenericClass<K> param);
Run Code Online (Sandbox Code Playgroud)
但它说:
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);
Run Code Online (Sandbox Code Playgroud)
其中说:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
那么,什么才是有效typedef的呢?
关于typedef,有两个“泛型”概念。typedef可以是类型上的泛型,或者typedef可以引用泛型函数(或两者):
一个typedef是通用的T:
typedef F<T> = T Function(T);
Run Code Online (Sandbox Code Playgroud)
然后在用法中:
F first = (dynamic arg) => arg; // F means F<dynamic>
F<String> second = (String arg) => arg; // F<String> means both T must be String
Run Code Online (Sandbox Code Playgroud)
一个typedef,它引用以下通用函数M:
typedef F = M Function<M>(M);
Run Code Online (Sandbox Code Playgroud)
然后在用法中:
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
Run Code Online (Sandbox Code Playgroud)
或两者:
typedef F<T> = M Function<M>(T,M);
Run Code Online (Sandbox Code Playgroud)
并在使用中:
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
781 次 |
| 最近记录: |