Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
466 views
in Technique[技术] by (71.8m points)

functional programming - Pass a typed function as a parameter in 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?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...