How to inject primitive variables in Kotlin?
Asked Answered
S

3

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

Schaumberger answered 23/6, 2017 at 9:13 Comment(4)
@JvmField @field:[Inject Named("isDemo")] var isDemo: Boolean = falseParesis
@Paresis and where is the Inject and Named annotations?!Schaumberger
@Paresis Thank you, it works!Schaumberger
@Paresis please add your answer. Upvoting comments is so boring.Sneaky
P
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
Paresis answered 23/6, 2017 at 12:22 Comment(2)
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 privateCinda
This works. Thanks. This is some mess. Hope dagger/kotlin solves this.Informal
L
5

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

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

Source

Lymanlymann answered 24/9, 2020 at 14:58 Comment(1)
For me works only accepted answer, not yours. In your case I'm getting error "Dagger does not support injection into private fields"Windy
E
0

If you are using Hilt and came across this question and also using your own qualified annotation, you can use this syntax too:

@Inject
@IsDemo
@JvmField 
var isDemo: Boolean = false
Edelman answered 10/1, 2024 at 10:43 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.