Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dagger Lazy during constructor injection

I realize that the recommended way of accomplishing Lazy injection with Dagger is to add Lazy to a field injection point. For instance,

class Foo {
    @Inject lateinit var bar: Lazy<Bar>

    fun useBar() = bar.get().doSomething()
}

What about using constructor injection? I have not seen anyone doing it.

class Foo @Inject constructor(private val fizz: Fizz,
                              private val bar: Lazy<Bar>) {    
    fun useBar() = bar.get().doSomething()
}

To summarize when doing Dagger lazy injection, can I use Lazy<Bar> in a constructor? Or is my only option to move Lazy<Bar> to a field injection while keeping other non-Lazy dependencies in the same class injected via the constructor?

Thanks for any pointers!

like image 644
liminal Avatar asked Jun 23 '26 18:06

liminal


1 Answers

Constructor injection is no different from regular field injection, Lazy-wrapped constructor arguments are acceptable.

The only thing you need to make sure is to expose the dependency via module somewhere in the dependency graph.

like image 71
dawid gdanski Avatar answered Jun 25 '26 13:06

dawid gdanski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!