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

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

问题描述

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

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 ,但是如果是我是否尝试过将它作为 Function< Integer> 传递,但Function并非如此?

For instance, in this case f is being invoked directly on an integer, but what if it was a function accepting a different 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 = new List<int Function(int)>[];

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

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

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