Skip to content

Type inference treated differently for nested functions. #373

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
jifalops opened this issue May 24, 2019 · 2 comments
Closed

Type inference treated differently for nested functions. #373

jifalops opened this issue May 24, 2019 · 2 comments
Labels
question Further information is requested

Comments

@jifalops
Copy link

jifalops commented May 24, 2019

See this SO post https://stackoverflow.com/a/56300558/884522.

This is what I get on Dartpad using 2.3.1:

foo() => 0;
bar() => [foo()];

main() {
  baz() => 0;
  qux() => [baz()];
  print(foo.runtimeType);    // () => dynamic
  print(bar.runtimeType);    // () => dynamic
  print(baz.runtimeType);   // () => int
  print(qux.runtimeType);   // () => List<int>
}

In the post, the user gets an error when assigning a List to the top level function, but not if the local/nested function is used.

var l = [1, 2, 3];
l = bar();            // Error
l = qux();           // Works

When in Dartpad, the error occurs at the same place but is different

TypeError: Instance of 'JSArray': type 'JSArray' is not a subtype of type 'List'

@lrhn
Copy link
Member

lrhn commented May 27, 2019

This is expected behavior.
Local functions use type inference to deduce their return type, but top-level/class-level functions do not.

The primary reason for the distinction is that top-level and class level functions exist at the same level as type declarations. Solving cyclic dependencies between types and functions gets even harder if we have to also analyze function bodies at a time where we don't even know the signature of classes yet.

When top-level inference has completed, we do know the type hierarchies, and where top-level functions are unordered, they can refer to each other in arbitrary ways, local functions are linear and can only depend on global functions or prior local functions. That means that we can analyze the function body locally to find the return type, without needing to look at anything except the body itself, and things we have already analyzed.

@lrhn lrhn added the question Further information is requested label May 27, 2019
@jifalops
Copy link
Author

Dup of dart-lang/sdk#33137

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Further information is requested
Projects
None yet
Development

No branches or pull requests

2 participants