https://kotlinlang.org logo
#dagger
Title
# dagger
s

Shawn Witte

10/14/2020, 9:37 PM
Is there a way to use
@Inject
on a Kotlin
object
or are my only options to convert it to a
class
or use
@Provides
?
1
c

coroutinedispatcher

10/16/2020, 2:19 PM
Well the thing is that
objects
live forever and they don't have a constructor. `object`s work like this: Once you call them the first time, they get instantiated and on the moment you access them again, the same created instance is accessed (if we can call it an instance). A short answer to your question would be No, but the thing is that you just don't need to use Dagger to provide or get it. You can of course create a function that provides that thing, but IMO that's an overkill
s

Shawn Witte

10/20/2020, 9:13 PM
The reason I asked is that I wanted to use the
object
as a constructor argument (which you can do) so it is a clearly defined dependency of the class. This means it is now something I know needs to be handled during testing (MockK can mock objects, which is nice). However, doing this means that Dagger needs to know how to provide the object. Hence I need to use
@Inject
or
@Provides
.
t

trevjones

10/24/2020, 8:53 PM
you can’t use
@Inject
on objects at all. you can however put it in the dagger graph with
@Provides
. Though I’d still recommend implementing an interface as an object and binding the object in the graph as the interface so that you don’t need to depend on fancy mocking tools to test any consumers.
3 Views