如何在Kotlin中注入原始变量? [英] How to inject primitive variables in Kotlin?

查看:149
本文介绍了如何在Kotlin中注入原始变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Android应用中使用Dagger2 for DI,并使用以下代码将类注入到Activity中很好:

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

但是,Kotlin的原始类型属性(例如Boolean)不允许使用lateinit修饰符,我该怎么做?

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

当我从此代码中删除lateinit时,出现此错误Dagger does not support injection into private fields

when I remove lateinit from this code I get this error Dagger does not support injection into private fields

推荐答案

首先,您不需要lateinit,可以将其保留为var,并使用任意值进行初始化. 其次,您必须公开一个字段,以允许Dagger注入该字段. 所以,这是解决方案:

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中注入原始变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆