Kotlin Dagger Injection From Java

Hi, I am writing kotlin files inside a java Android project, and having some problem when I tried to inject field from a java module.

The dagger injected variable in java file looks like

@Inject @Identifier boolean isTablet

and I copied this line to my kotlin file, it got converted to

@Inject @Identifier internal var isTablet: Boolean = false

I can’t remove “= false” because AS shows “Property must be initialized or be abstract” error

What’s the correct syntax I should use to properly inject variable from java file?

The syntax you’re using is correct; there’s nothing better. For variables of object types, you can use lateinit, but it’s not supported for a Boolean.

The problem I noticed that is I initialized it to false, it seems won’t change based on the module

@Inject @Identifier internal var isTablet: Boolean = false

The problem of this way is that I got

java.lang.IllegalStateException: Can’t inject private field

When I tried to run it, any idea how it can be solved?

I faced the same issue. Unfortunatelly i don’t remember how i fixed it. But you can use constructor injection as a workaround.

I saw this stackoverflow post display how to use constructor injection to replace field injection, unfortunately, I am injecting to the test so neither class nor method I can add arguments. Any workaround?

Well. Try to make your variable public not internal.

Some other possibilities ( I am on my phone so I can’t test them for you):

You didn’t say if this was dagger 1 or 2, but dagger 2 supports method injection so you can say @set:Inject to annotate the setter method instead of the field.

There is also @JvmField to make the field public to Java.