Using Kotlin with Dagger

Kirill Rakhman picture Kirill Rakhman · Oct 17, 2014 · Viewed 7.4k times · Source

What's the best way to use Dagger to inject dependencies into classes, especially zero-arg constructor classes like Activities, with Dagger? Will Dagger 2 possibly bring improvements to the situation?

Thanks in advance.

Answer

Ben picture Ben · Sep 16, 2015

Since Kotlin M13 release, a new property has been especially added in order to support dependency injection (like with Dagger 1&2) and other frameworks.

It's called lateinit property. Taken from the documentation:

 class Example {
            @Inject
            lateinit var bar: Bar 
 }

In a nutshell, bar has no initializers but is declared as a non-null type. If you try to read it before the initialization, an exception is thrown.
Otherwise, once it's initialized using Dagger, it can be used as a normal property.

Everything is well explained in the language doc and you can also check the blog post relative to the M13 release there.