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?
Dart has three ways to declare parameters for a function.
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.
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.
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;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With