I am using Dagger2 for DI in my Android app, and using this code for injecting classes into my Activity is fine:
@field:[Inject ApplicationContext]
lateinit var context: Context
but, lateinit
modifier is not allowed on primitive type properties in Kotlin (for instance Boolean
), how can I do something like this?
@field:[Inject Named("isDemo")]
lateinit var isDemo: Boolean
when I remove lateinit
from this code I get this error Dagger does not support injection into private fields
@Inject is a Java annotation for describing the dependencies of a class that is part of Java EE (now called Jakarta EE). It is part of CDI (Contexts and Dependency Injection) which is a standard dependency injection framework included in Java EE 6 and higher.
Kotlin uses two different keywords to declare variables: val and var . Use val for a variable whose value never changes. You can't reassign a value to a variable that was declared using val . Use var for a variable whose value can change.
Kotlin doesn't have primitive type (I mean you cannot declare primitive directly). It uses classes like Int , Float as an object wrapper for primitives. When kotlin code is converted to jvm code, whenever possible, "primitive object" is converted to java primitive.
First, you don't need lateinit
, you can leave it as a var
, and initialize with an arbitrary value.
Second, you must expose a field in order to allow Dagger to inject there.
So, here's the solution:
@JvmField // expose a field
@field:[Inject Named("isDemo")] // leave your annotatios unchanged
var isDemo: Boolean = false // set a default value
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With