-
Notifications
You must be signed in to change notification settings - Fork 209
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
Support inferring the return value of functions #4280
Comments
We could use Its also something used in other languages, like Kotlin (from documentation): fun main() {
// T is inferred as String because SomeImplementation derives from SomeClass<String>
val s = Runner.run<SomeImplementation, _>()
assert(s == "Test")
// T is inferred as Int because OtherImplementation derives from SomeClass<Int>
val n = Runner.run<OtherImplementation, _>()
assert(n == 42)
} So, in Dart, it would be: _ example() => (name: '', age: 42); |
I don't mind. I proposed class Bloc<BlocT extends Bloc<infer StateT>> {} |
You're not forced to write the return type everywhere. void main() {
example() => (name: '', age: 42);
print([example].runtimeType); // prints: List<() => ({String name, int age})>
} This shows that the return type of the There is a difference between top-level inference and local inference. Take: class Foo {
Foo? next;
foo() => switch (next) { null => "42", var next? => next.foo() };
} To infer the return type of Rather than trying to design a complete constraint gathering and solving system, Dart just requires top-level declarations to be typed. Then the types and members are well-defined, and it can do better inside function bodies. |
I'd expect it to behave exactly like: class Foo {
Foo? next;
late final foo = () => switch (next) { null => "42", var next? => next.foo() };
} That is: The request is only about supporting whatever closures support. |
I get top-level inference with Could we have a package-wide setting to enable return type inference? Because prefixing the function with |
I think the approach proposed by @Wdestroier is preferable. If we had an analyzer setting for analyzer:
language:
strict-inference: true then all inferences in the code base must resolve to a non-dynamic type, an error is reported if inference fails in which case the type should be explicitly annotated. This is preferable because it does not require additional repetitive syntax that would likely appear across many declarations. |
With records, it becomes tempting to rely more on type-inference. Inference is important for records, because it avoids lots of repetition
The problem is, inference for the return value of function is only available with closures:
If we use a "normal" function, we are forced to specify the return value:
Proposal
It'd be cool to have a mean to define classical functions, but infer the value. One possibility could be:
The text was updated successfully, but these errors were encountered: