I updated from dagger 2.21 to dagger 2.27 and now ...
# dagger
c
I updated from dagger 2.21 to dagger 2.27 and now I see errors when compiling
error: Dagger does not support injection into Kotlin objects
I'm admittedly someone still very new to dagger and so I'm not sure if I'm violating some overarching DI rules with trying to inject my moshi instance into my "util object". Can someone point me in the right direction of a solution? I suppose I can write extension methods instead of having this java util that was converted to a kotlin object?
p
Show the code that fails
s
According to release notes, it is not allowed any more https://github.com/google/dagger/releases
c
@Sinan Kozak do you happen to know what the best workaround is for this?
s
Nope, i never injected in object class.
p
@Colton Idle You could use a dependency holder class
I.e.
Copy code
object MySingleton{

  class Deps @Inject constructor(
    val depA : Int
  )

  lateinit var deps : Deps
}

fun initSingleton(){
  MySingleton.deps = component.deps
}
But youre better of just using class and let dagger manage the singletons in the first place
j
Yes, you probably want
@Singleton
c
So I need to convert all of my old school style Java util classes/methods to a singleton and then inject that everywhere? Hrm. Not in love with that idea, but I guess it'll work. Maybe I could get away with what @Paul Woitaschek said for now. I don't want to make a bunch of changes to other classes that just so happen to use different utils.
p
Then keep in in java
☝️ 1
j
Dagger works equally well w/ Kotlin and Java but if you want Dagger to manage your Singleton dependencies need to make some minor changes
Singleton
is not the same as
static
and kotlin
object
c
Understood, it's just that I have a static util, and I'm not trying to make that static util class a
@Singleton
. I'm instead trying to inject a singleton into that util so I can make sure it uses the same moshi instances. I guess at this point I'll just reevaluate the whole thing.
j
Yah I'd avoid using
object
singletons to maintain global state but if you wanted to retain it you'd probably manually inject the moshi
If nothing else it will be difficult to test
c
The
object
at hand doesn't handle any global state. It's just contains 4 util methods that rely on moshi to convert some json payloads to certain types.
s
Create moshi in util class provide it to dagger from util class.
p
Then Moshi is the global state
If it's only Moshi use a by lazy and get Moshi from the component
c
Hm. This is all really going over my head. 😞 I might play around with this later. Appreciate all of the help. I think I might try to get rid of my util and just make extension functions and see if that helps.