3

Let's say i have an interface named as interfaceA

interface InterfaceA {}

And it's concrete implementation with Assisted inject

class ImplClass @AssistedInject constructor(@Assisted someClass:SomeCLass):InterfaceA {
}

How would you go about using Assisted Inject in this case, where dagger also requires binding of concrete class with the interface.

Is below the correct way? or i am missing something?

class ImplClass @AssistedInject constructor(@Assisted someClass:SomeCLass):InterfaceA {

    @AssistedFactory
    interface DaggerFactory : Factory {
      override fun create(someClass:SomeCLass): ImplClass
    }

    interface Factory {
     fun create(someClass:SomeCLass): InterfaceA
    }              
}

and then, bind it like this

@Module
@InstallIn(ActivityComponent::class)
interface BindsSomething {
  @Binds
  fun binds(factory: ImplClass.DaggerFactory): ImplClass.Factory
}

The above approach works though, I am wondering if there is a better way or a different way with less boiler-plate, which i am not aware of.

Ritt
  • 3,181
  • 3
  • 22
  • 51

1 Answers1

1

This seems to be the only way. I have looked up entire documentation there is no alternative way of declaring @AssistedFactory that will create concrete instance of an interface.

A slight improvement would be moving the Factory in InterfaceA then binding that Factory interface. This would logically separate your factory from the concrete implementation:

@Module
@InstallIn(ActivityComponent::class)
interface BindsSomething {
  @Binds
  fun binds(factory: ImplClass.DaggerFactory): InterfaceA.Factory
}

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