Created
November 22, 2015 04:06
-
-
Save bjconlan/1f58f012c73347681803 to your computer and use it in GitHub Desktop.
Kotlin Dagger Example
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
import dagger.Component | |
import dagger.Module | |
import dagger.Provides | |
import javax.inject.Inject | |
import javax.inject.Singleton | |
interface Heater { | |
fun on() | |
fun off() | |
} | |
interface Pump { | |
fun pump() | |
} | |
@Module | |
class PumpModule { | |
@Provides fun providePump(): Pump = object : Pump { | |
override fun pump() = println("=> => pumping => =>") | |
} | |
} | |
@Module(includes = arrayOf(PumpModule::class)) | |
class DripCoffeeModule() { | |
@Provides fun provideHeater(): Heater = object : Heater { | |
override fun on() = println("~ ~ ~ heating ~ ~ ~") | |
override fun off() {} | |
} | |
} | |
class CoffeeMaker | |
@Inject constructor(val heater: dagger.Lazy<Heater>, | |
val pump: Pump) { | |
init { | |
heater.get().on() | |
pump.pump() | |
println(" [_]P coffee! [_]P") | |
heater.get().off() | |
} | |
} | |
@Singleton | |
@Component(modules = arrayOf(DripCoffeeModule::class)) | |
interface CoffeeShop { | |
fun maker(): CoffeeMaker | |
} | |
fun main(args: Array<String>) { | |
val coffeeShop = DaggerCoffeeShop.create() | |
coffeeShop.maker() | |
} |
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
buildscript { | |
ext { | |
kotlinVersion = '1.0.0-beta-2423' | |
daggerVersion = '2.0.2' | |
} | |
repositories { | |
jcenter() | |
} | |
dependencies { | |
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion" | |
} | |
} | |
apply plugin: 'kotlin' | |
repositories { | |
jcenter() | |
} | |
kapt { | |
generateStubs = true | |
} | |
dependencies { | |
kapt "com.google.dagger:dagger-compiler:$daggerVersion" | |
compile "com.google.dagger:dagger:$daggerVersion" | |
compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlinVersion" | |
} | |
sourceSets { | |
main.java.srcDirs += 'src/main/kotlin' | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment