World Shortest Dagger 2 Code?

I once wish someone give me a very small piece of code explaining what how Dagger 2 works. Doesn’t need to be complete, but the gist of it.

Can’t find one, so I provide one below. (Didn’t find any one shorter than this one, so I think it’s world shortest 😝.

The code

Let’s look at the code directly.

fun main(args: Array<String>) {
println(MainClass().info.text)
}

class MainClass {
@Inject lateinit var info : Info
init {
DaggerMagicBox.create().poke(this)
}
}

class Info @Inject constructor() {
val text = "Hello Dagger 2"
}

@Component interface MagicBox {
fun poke(mainClass: MainClass)
}

Try studies the code, hopes it’s not too confusing.

The main special part is the info within MainClass is not instantiated, but it is still usable. The magic happens after DaggerMagicBox.create().poke(this).

The DaggerMagicBox.create().poke(this) is just telling the MagicBox to help automatically create all the member variables of MainClass that has the @Inject annotation.

Don’t worry about the implementation of @Component annotated MagicBox. It is what the Dagger 2 handles (auto generate the needed code, and stitch up the injection).

--

--