-
-
Save goj/defb14a6232064a0a4beb7d77913e8c3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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