22

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

Mohsen Mirhoseini
  • 8,454
  • 5
  • 34
  • 59

2 Answers2

42

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
Miha_x64
  • 5,973
  • 1
  • 41
  • 63
  • 1
    Maybe you should think of a `protected` true if you want to protect your property to be accessed (and changed) just in (sub-)classes - works with Dagger because this won't result in `private` – r00tandy Jul 19 '17 at 04:03
  • This works. Thanks. This is some mess. Hope dagger/kotlin solves this. – rpattabi Dec 09 '19 at 06:39
5

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

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

Source

Mohamed Medhat
  • 761
  • 11
  • 16
  • For me works only accepted answer, not yours. In your case I'm getting error "Dagger does not support injection into private fields" – JerabekJakub May 04 '21 at 11:36