Skip to content

Unexpected behavior when using () -> T to break a cycle #286

Open
@damianw

Description

@damianw

If a provision has @Assisted injection parameters and injects a factory function for its own type, the code generated for the factory function unexpectedly ignores the assisted arguments and returns a single instance. For example:

@Inject
class MyDep(
    private val factory: (id: Int) -> MyDep,
    @Assisted val id: Int
) {

    fun next(): MyDep = factory(id + 1)
}

@Component
interface MyComponent {

    val myDepFactory: (id: Int) -> MyDep
}

Produces the following code:

public fun KClass<MyComponent>.create(): MyComponent = InjectMyComponent()

public class InjectMyComponent : MyComponent {
  public override val myDepFactory: Function1<Int, MyDep>
    get() = { arg0 ->
      run {
        lateinit var myDep: MyDep
        MyDep(
          factory = { arg0_ ->
            myDep
          },
          id = arg0
        ).also {
          myDep = it
        }
      }

    }
}

Note that arg0_ is ignored, and the same instance is always returned. In this example, calling next() would return the same instance it was called on. This happens with @Provides in addition to @Inject.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions