1

The goal is to inject a class with an optional constructor parameter.

If using @Inject the class will be created without the optional parameter, while if I want to pass the optional parameter I can use a factory @AssistedFactory.

I am trying to achieve it like this:

class ClassName @AssistedInject constructor(
    private val database: FirebaseFirestore,
    private val functions: FirebaseFunctions,
    @Assisted private val division: String?
) {

    @Inject constructor(
        database: FirebaseFirestore,
        functions: FirebaseFunctions
    ) : this(database, functions, null)
}

But it throws an error when I am injecting ClassName without using a factory

error: Dagger does not support injecting @AssistedInject type, ClassName. Did you mean to inject its assisted factory type instead?

How can I achieve the goal above? Any help is much appreciated

1 Answers1

1

That's not possible, @AssistedInject annotation is processed in a way such that the target injecting class must match the argument number and type in the factory.

However you can remove the @Inject and create provider function that will receive the assisted factory as dependecy

@Provides 
fun providesClassName(classNameFactory : ClassName.Factory) : ClassName{
   return classNameFactory.create(null)
}

Elsewhere you can just use assisted factory as usual:

@Inject classNameAssistedFactory : ClassName.Factory

override fun onCreate(...){
  super.onCreate(...)
  classNameAssistedFactory.create("divisionA")
}


Nikola Despotoski
  • 49,966
  • 15
  • 119
  • 148