如何使用具有参数化返回类型的函数参数调用函数



我对dart的理解是,Function<T>()是一个表示返回类型为T的函数的类型。因此,如果我想提供这样的函数作为回调:

T wrapper<T>(Function<T>() f){
return f();
}

。编译。

但是当调用包装器并提供具有某种返回类型的函数时,我得到:

int myF()=>123;
callWrapper(){
int i = wrapper(myF);  <<< error with myF
}
error: The argument type 'int Function()' can't be assigned to the parameter type 'dynamic Function<T>()'. (argument_type_not_assignable at ....

我不明白。为什么类型检查器认为int Function()Function<T>()不匹配?

也以同样的方式失败:

T wrapper<T>(T Function() f){    ///<<<<
return f();
}
int myF()=>123;
callWrapper(){
int i = wrapper(myF);
}

这里的问题是参数Function<T>() f并不是说"f一个不带参数并返回TFunction",它实际上是在说"f是一个不带参数并返回dynamicFunction<T>"。

有两种方法可以完成此操作:

1.

T wrapper<T>(T Function() f) { ... }

阿拉伯数字。

T wrapper<T>(T f()) { ... }

dart:coreFunction类没有任何类型变量。我认为分析器应该警告你不要做Function<T>()但事实并非如此。

最新更新