How to inject primitive variables in Kotlin?

旧城冷巷雨未停 提交于 2020-03-13 05:56:58

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/44717566/how-to-inject-primitive-variables-in-kotlin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!