是否可以将类型参数信息传递给匕首子组件?

时间:2020-03-15 10:15:14

标签: generics kotlin dagger subcomponent

我希望能够向通用抽象类中的子组件公开类型信息。我们有一个g++ -o test -g main.cpp { time ./test ; } 2>&1> /home/kj/bashTest/log ,其类型参数在子类中设置(后者在我们的图形中绑定),然后尝试将此类型信息传递给该类内的子组件。尝试的方式尝试将类型参数附加到子组件。

这里是我想要实现的更加充实的示例:

abstract class

当然,这不会:

interface Runner<T> {
    fun run(t: T)
}

data class Data<T>(
    val options: T
)

abstract class AbstractRunner<Options> : Runner<Data<Options>> {

    @Inject
    lateinit var mySubcomponentBuilder: MySubcomponent.Builder<Options>

    // Constructing this relies on dynamicData which must be generated at runtime
    // (hence the subcomponent)
    // @Inject
    // lateinit var subRunner: Runner<Options>

    override fun run(data: Data<Options>) {

        // Some dynamically generated data - we can't use assisted injection as this is injected into other classes in
        // the subgraph.
        val dynamicData = Random.nextInt()

        mySubcomponentBuilder
            .dynamicData(dynamicData)
            .build()
            .subcomponentRunner()
            .run(data.options)
    }
}

// We have other objects with associated Runner implementations;
// we list one for brevity.
object Foo
class MyRunner @Inject constructor() : AbstractRunner<Foo>()
class SubRunner @Inject constructor(s: String) : Runner<Foo> {
    override fun run(t: Foo) {}
}

@Component(modules=[MyModule::class])
interface MyComponent {
    fun runner(): Runner<Data<Foo>>
}

@Module(subcomponents=[MySubcomponent::class])
interface MyModule {
    @Binds
    fun bindMyRunner(runner: MyRunner): Runner<Data<Foo>>
}

// This does not work due to generics being banned on (Sub)Components.
@Subcomponent(modules=[SubModule::class])
interface MySubcomponent<T> {
    // We can't parameterise the method; generics are banned on methods in (Sub)Components.
    fun subcomponentRunner(): Runner<T>

    @Subcomponent.Builder
    interface Builder<U> {
        @BindsInstance
        fun dynamicData(i: Int): Builder<U>
        fun build(): MySubcomponent<U>
    }
}

@Module
object SubModule {
    @Provides
    fun provideString(i: Int) = i.toString()
    @Provides
    fun provideSubRunner(s: String): Runner<Foo> = SubRunner(s)
}

是否可以通过其他方式浏览此信息?如注释所示,如果不需要子组件中绑定的变量,则可以将error: @Subcomponent.Builder types must not have any generic types 绑定到主图中而不会出现问题。

0 个答案:

没有答案