Skip to content

Generic type inference fails when return value is inside an assignment #4491

@rubenferreira97

Description

@rubenferreira97

When calling a generic function without explicit type parameters, the compiler fails to infer the correct type if the result is wrapped in an assignment expression, even if the surrounding context makes the expected type unambiguous.

T id<T>(T value) => value;

class A {
  int? value;

  int bad() {
    // Error:
    // A value of type 'int?' can't be returned from the method 'bad'
    // because it has a return type of 'int'.
    return value = id(42); // compiler infers `id<int?>(42)`
  }

  int good() {
    // Works fine when explicitly specifying type argument.
    return value = id<int>(42);
  }
}

Expected behavior:
The compiler should be able to infer T = int from the surrounding return type, even though the result is assigned to an int? variable.


I would not be surprised if both examples failed, since I expect the compiler to first assign and then return:

  int bad2() {
    value = id(42); // infers id<int?>(42) correctly, because the only context type is `int?`
    return value;
  }

But the good does something different. Is it possible to be smarter here and infer the correct type?

Metadata

Metadata

Assignees

No one assigned

    Labels

    requestRequests to resolve a particular developer problem

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions