Last active
December 17, 2025 15:59
-
-
Save jclyne/bff848e67b998121369528b365615ea7 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| import com.google.inject.AbstractModule | |
| import com.google.inject.Guice | |
| import com.google.inject.multibindings.OptionalBinder | |
| import jakarta.inject.Inject | |
| import java.util.Optional | |
| import kotlin.jvm.optionals.getOrNull | |
| class Greeter(val name: String) { | |
| fun greet() = println("Hello $name") | |
| } | |
| class Director(val direction: String) { | |
| fun direct() = println("Go $direction") | |
| } | |
| class Application @Inject constructor( | |
| private val greeter: Greeter, | |
| private val director: Optional<Director>, | |
| ) { | |
| fun run() { | |
| greeter.greet() | |
| director.getOrNull()?.direct() | |
| } | |
| } | |
| class OptionalModule : AbstractModule() { | |
| override fun configure() { | |
| OptionalBinder.newOptionalBinder(binder(), Greeter::class.java) | |
| OptionalBinder.newOptionalBinder(binder(), Director::class.java) | |
| } | |
| } | |
| class GreeterModule : AbstractModule() { | |
| override fun configure() { | |
| bind(Greeter::class.java).toProvider { Greeter("builder") } | |
| } | |
| } | |
| class DirectorModule : AbstractModule() { | |
| override fun configure() { | |
| bind(Director::class.java).toProvider { Director("east") } | |
| } | |
| } | |
| class AppModule: AbstractModule() { | |
| override fun configure() { | |
| install(GreeterModule()) | |
| install(DirectorModule()) | |
| install (OptionalModule()) | |
| } | |
| } | |
| fun main(){ | |
| val injector = Guice.createInjector(AppModule()) | |
| val app = injector.getInstance(Application::class.java) | |
| app.run() | |
| } | |
| Output: | |
| Hello builder | |
| Go east |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment