Pass a typed function as a parameter in Dart

给你一囗甜甜゛ 提交于 2020-01-21 00:58:26

问题


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?

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

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?


回答1:


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;



回答2:


Edit: Note that this answer contains outdated information. See Irn's answer for more up-to-date information.

Just to expand on Randal's answer, your code might look something like:

typedef void IntegerArgument(int x);

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

Function<int> seems like it would be a nice idea but the problem is that we might want to specify return type as well as the type of an arbitrary number of arguments.




回答3:


You can have a function typed parameter or use a typedef

void main() {
  doSomething(xToString);
  doSomething2(xToString);
}

String xToString(int s) => 's';

typedef String XToStringFn(int s);

void doSomething(String f(int s)) {
    print('value: ${f(123)}');
}

void doSomething2(XToStringFn f) {
    print('value: ${f(123)}');
}

DartPad example




回答4:


This is what typedefs are for!




回答5:


For reference.

int execute(int func(int a, int b)) => func(4, 3);

print(execute((a, b) => a + b));


来源:https://stackoverflow.com/questions/43334714/pass-a-typed-function-as-a-parameter-in-dart

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!