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

推荐答案

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

Kotlin相关问答推荐

相当于roomdb中的DateTime Bigint列的是什么

数据源配置

在Kotlin中的嵌套when语句中,else块是强制性的吗?

为何Kotlin标准库中的AND和OR函数不能像&&和||一样进行短路运算?

Kotlin:调用 CoroutineScope.launch 与在协程内启动之间的区别

Jetpack Compose 中的连续重组

Kotlin 具体类从抽象类和接口扩展而来,接口使用抽象类中实现的方法

正则表达式 FindAll 不打印结果 Kotlin

Jetpack BottomNavigation - java.lang.IllegalStateException:Already attached to lifecycleOwner

Kotlin 有垃圾收集器吗?如果是这样,它基于哪种算法?

如何创建 Kotlin DSL - DSL 语法 Kotlin

Kotlin 中 lambda 表达式中的默认参数

将 jetpack compose 添加到现有元素

Kotlin - mutableMapOf() 会保留我输入的顺序

Kotlin 的 Double.toInt() 中使用了哪种方法,舍入还是截断?

Jetpack Compose-居中文本

如果作为 RxJava Observable 提供,Kotlin 密封类子类需要强制转换为基类

这是 Kotlin 中的错误还是我遗漏了什么?

Kotlin - computed var 属性的用处?

尾随 lambda 语法(Kotlin)的目的是什么?