[AssistedInject] Validate that parameters names match between factory method and the constructor
See original GitHub issueWith 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.
Issue Analytics
- State:
- Created 3 years ago
- Reactions:2
- Comments:16 (4 by maintainers)
Top GitHub Comments
Aren’t qualifiers more natural for Dagger than some custom parameter for
@Assisted
annotation? In this case, it would be much more flexible. Those who want to useString
constants to disambiguate the types could use the@Named
qualifier in this case. And those who like a more declarative (IMO) way of using custom qualifiers would not need to switch toString
constants. Also, switch to assisted injection for existing classes would be much easier if qualifiers already there.For the record, Guice attaches the disambiguation name to the
@Assisted
annotation: https://google.github.io/guice/api-docs/latest/javadoc/com/google/inject/assistedinject/Assisted.html See “Making parameter types distinct” in https://google.github.io/guice/api-docs/latest/javadoc/com/google/inject/assistedinject/FactoryModuleBuilder.html