Search code examples
dependency-injectiondaggerkotlindagger-2

Using Kotlin with Dagger


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.


Solution

  • 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.