Search code examples
functional-programmingdart

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?


Solution

  • 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;