dart lambda type inference

Viewed 42
void main() {
  print(doStuff.runtimeType);
  print(((e) => doStuff(e)).runtimeType);
}

int doStuff(String hallo) {
  return 42;
}

executed in the dartpad yields

(String) => int
(dynamic) => int

I would expect both to have the same type. Can somebody explain why dart fails to infer the type of the argument e?

1 Answers

Dart type inference is limited in some ways that inference in purely functional languages is not. It's not constraint solving based.

So, when the compiler sees (e) => doStuff(e), it checks whether there is a context type from which it can deduce the parameter type. There isn't (being the receiver of .runtimeType provides no hint). So, it infers dynamic for the parameter, which needs a type before the body of the function can be type analyzed at all.

Then it looks at the body and sees that doStuff(e) is valid and has type int, so that becomes the return type.

Related