在 Dart 中将类型化函数作为参数传递 [英] Pass a typed function as a parameter in Dart

查看:43
本文介绍了在 Dart 中将类型化函数作为参数传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道函数 类可以作为参数传递给另一个函数,如下所示:

I know the Function class can be passed as a parameter to another function, like this:

void doSomething(Function f) {
    f(123);
}

但是有没有办法限制参数和函数参数的返回类型?

But is there a way to constrain the arguments and the return type of the function parameter?

例如,在这种情况下,f 是直接在一个整数上调用的,但如果它是一个接受不同类型的函数呢?

For instance, in this case f is being invoked directly on an integer, but what if it was a function accepting a different type?

我尝试将其作为 Function 传递,但 Function 不是参数类型.

I tried passing it as a Function<Integer>, but Function is not a parametric type.

有没有其他方法可以指定作为参数传递的函数的签名?

Is there any other way to specify the signature of the function being passed as a parameter?

推荐答案

Dart v1.23 添加了一种用于编写函数类型的新语法,该语法也可以在线运行.

Dart v1.23 added a new syntax for writing function types which also works in-line.

void doSomething(Function(int) f) {
  f(123);
}

与函数参数语法相比,它的优势在于您还可以将其用于变量或其他任何您想编写类型的地方.

It has the advantage over the function-parameter syntax that you can also use it for variables or anywhere else you want to write a type.

void doSomething(Function(int) f) {
  Function(int) g = f;
  g(123);
}

var x = <int Function(int)>[];

int Function(int) returnsAFunction() => (int x) => x + 1;
    
int Function(int) Function() functionValue = returnsAFunction;

这篇关于在 Dart 中将类型化函数作为参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆