Skip to content

[AssistedInject] Validate that parameters names match between factory method and the constructor #2281

@lwasyl

Description

@lwasyl

With the following code:

package com.example

import dagger.Component
import dagger.assisted.Assisted
import dagger.assisted.AssistedFactory
import dagger.assisted.AssistedInject

class NamingRepro @AssistedInject constructor(
    @Assisted private val foo: String,
    @Assisted private val bar: String,
) {

    @AssistedFactory
    interface Factory {
        fun create(
            bar: String,
            foo: String
        ): NamingRepro
    }

    fun print() {
        println("""
            Passed foo: $foo,
            passed bar: $bar
        """.trimIndent())
    }
}

@Component
interface NamingComponent {

    fun repro(): NamingRepro.Factory
}

Dagger will ignore the fact that foo and bar parameters order is different in the create method and the constructor. The generated factory will then pass arguments from create to the constructor in unexpected (or expected, but clearly not intentional) order. So:

DaggerNamingComponent.create()
    .repro()
    .create(bar = "bar", foo = "foo")
    .print()

will print

Passed foo: bar,
passed bar: foo

This is error prone and difficult to prevent using automated tools. It would be great if Dagger verified the parameters names as well, requiring them to match between the factory method and the constructor.

Also as far as I understand, square/AssistedInject doesn't verify the parameters order, but forces matching names (if there were more than one parameter with the same type). This can lead to some confusing migration errors, as now the behavior is the opposite.

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions