safsaf32
safsaf32

Reputation: 1587

Return type of an anonymous function

I am reading about dart and one think that confuses me is the the syntax for anonymous functions. Specifically, how do I specify the type of the returned value for such a function.

For example, consider the following:

var f = (int x) {return x + 1;};

In this instance, I am declaring that the type of the parameter x is int. How can I explicitly say that the function returns an int? I understand that the compiler will probably figure that out using type inference, but I want to explicitly specify the type to prevent the possibility of returning a value of the wrong type when writing more complex functions.

Upvotes: 30

Views: 15112

Answers (5)

Praise Dare
Praise Dare

Reputation: 540

Function expressions in dart can't be named.

print(int anonFunc () {}) // ERROR: Function expressions can't be named.

Now if we try to take out the name and leave only the type instead:

print (int () { return 20; });

We still get the original error because dart thinks that int is now the name of the closure.

So in short, it's just not possible to have return types for anonymous functions in dart.

If you plan on passing the closure as an argument to another function, then the best you can do is to add type annotations to the parameter of the higher order function receiving the closure like so:


int callClosureWithArg(int Function(int x) func, int y) {
    return func(y);
}

// Now you will get a compile error if the closure's signature
// doesn't match with the parameter's signature
callClosureWithArg((String x) {
    return x.length;
})

Upvotes: 0

BMFA
BMFA

Reputation: 11

THE ANONYMOUS DART FUNCTION USES A dynamic data type on retrun

Upvotes: -1

Serge Shkurko
Serge Shkurko

Reputation: 51

Also you can use typedef if you plan to use inline function type several times

typedef CalcCallback = int Function(int a, int b);

enum Operation {
  sum,
  diff,
}

CalcCallback calc(Operation operation) {
  CalcCallback sum = (int a, int b) => a + b;
  CalcCallback diff = (int a, int b) => a - b;

  return operation == Operation.sum ? sum : diff;
}


void main() {
  print(calc(Operation.sum)(5, 5)); // 10
  print(calc(Operation.diff)(20, 5)); // 15
}

Upvotes: 0

Mattia
Mattia

Reputation: 6524

You can do something like this:

int Function(int x) f = (int x) {return 1 + x;};
String Function(String x, String y) concatenate = (String x, String y) {return '$x$y';};

EDIT: Here is a simpler way using type casting:

int f = (int x) {return x + 1;} as int;

Upvotes: 25

Kevin Moore
Kevin Moore

Reputation: 6161

You can declare an anonymous, inline function just like a regular function

int count(int a, int b) {
  int innerThing(int c, int d) => c + d;

  return innerThing(a, b);
}

That might be easier.

Upvotes: 6

Related Questions