19
votes

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

2
@JvmField @field:[Inject Named("isDemo")] var isDemo: Boolean = false - Miha_x64
@Miha_x64 and where is the Inject and Named annotations?! - Mohsen Mirhoseini
@Miha_x64 Thank you, it works! - Mohsen Mirhoseini
@Miha_x64 please add your answer. Upvoting comments is so boring. - tynn

2 Answers

39
votes

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
5
votes

The accepted answer didn't work with me, but the following worked well:

@set:[Inject Named("isDemo")]
var isDemo: Boolean = false

Source