Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 505
Raibaz Avatar asked Apr 11 '17 00:04

Raibaz


People also ask

How many ways you can pass the parameters in Dart?

Dart has three ways to declare parameters for a function.

How do you assign a variable to a function in Dart?

Dart function simple exampleint z = add(x, y); We call the add function; it takes two parameters. The computed value is passed to the z variable. The definition of the add function starts with its return value type.

What is type annotation in Dart?

The Dart language is type safe: it uses a combination of static type checking and runtime checks to ensure that a variable's value always matches the variable's static type, sometimes referred to as sound typing. Although types are mandatory, type annotations are optional because of type inference.


2 Answers

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; 
like image 137
lrn Avatar answered Sep 27 '22 00:09

lrn


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.

like image 24
Richard Ambler Avatar answered Sep 25 '22 00:09

Richard Ambler