Skip to content

Instantly share code, notes, and snippets.

@goj
Last active February 8, 2024 16:55
Show Gist options
  • Save goj/defb14a6232064a0a4beb7d77913e8c3 to your computer and use it in GitHub Desktop.
Save goj/defb14a6232064a0a4beb7d77913e8c3 to your computer and use it in GitHub Desktop.
package com.google.bugs.daggerchild
import dagger.Binds
import dagger.BindsOptionalOf
import dagger.Component
import dagger.Module
import dagger.Provides
import dagger.Subcomponent
import java.util.Optional
import javax.inject.Inject
import javax.inject.Qualifier
import javax.inject.Singleton
interface Coffee
data object Sugar
class JudgmentalCoffee @Inject internal constructor(private val sugar: Optional<Sugar>): Coffee {
override fun toString() = if (sugar.isPresent) "unhealthy coffee" else "healthy coffee"
}
@Module
internal interface ParentModule {
@Binds fun coffee(impl: JudgmentalCoffee): Coffee
@BindsOptionalOf fun sugar(): Sugar
}
@Qualifier annotation class Opinion
@Module
internal object ChildModule {
@Provides fun sugar() = Sugar
@Provides @Opinion fun opinion(coffee: Coffee) = "you drink $coffee"
}
@Subcomponent(modules = [ChildModule::class])
interface ChildComponent {
@Opinion fun opinion(): String
}
@Singleton
@Component(modules = [ParentModule::class])
interface ParentComponent {
fun child(): ChildComponent
}
fun main() {
println(DaggerParentComponent.create().child().opinion())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment