如何使用 dagger 2 和 kotlin 在 activity 中注入可空类型
How to filed inject a nullable type in an activity with dagger 2 and kotlin
我有一个 this 依赖项,我想注入一些 activity。我正在使用 dagger.android
并完成所有设置并且项目编译完美
在 AppModule 中:
@Provides
fun provideAppDrawable(application: Application): Drawable? {
return ContextCompat.getDrawable(application, R.drawable.logo)
}
在activity中:
@Inject lateinit var logo: Drawable
现在,当我尝试 运行 应用程序时,Dagger 2 会抛出此错误 error: [Dagger/Nullable] android.graphics.drawable.Drawable is not nullable
有办法解决这个问题吗?谢谢
这是关于 kotlin 中的 Null Safety。来自 Documentation:
In Kotlin, the type system distinguishes between references that can
hold null (nullable references) and those that can not (non-null
references). For example, a regular variable of type String can not hold null:
var a: String = "abc"
a = null // compilation error
To allow nulls, we can declare a variable as nullable string, written String?:
var b: String? = "abc"
b = null // ok
因此,您必须提供 Drawable
(不带?),或者将 activity 中的变量类型更改为 Drawable?
(带?)。
我有一个 this 依赖项,我想注入一些 activity。我正在使用 dagger.android
并完成所有设置并且项目编译完美
在 AppModule 中:
@Provides
fun provideAppDrawable(application: Application): Drawable? {
return ContextCompat.getDrawable(application, R.drawable.logo)
}
在activity中:
@Inject lateinit var logo: Drawable
现在,当我尝试 运行 应用程序时,Dagger 2 会抛出此错误 error: [Dagger/Nullable] android.graphics.drawable.Drawable is not nullable
有办法解决这个问题吗?谢谢
这是关于 kotlin 中的 Null Safety。来自 Documentation:
In Kotlin, the type system distinguishes between references that can hold null (nullable references) and those that can not (non-null references). For example, a regular variable of type String can not hold null:
var a: String = "abc" a = null // compilation error
To allow nulls, we can declare a variable as nullable string, written String?:
var b: String? = "abc" b = null // ok
因此,您必须提供 Drawable
(不带?),或者将 activity 中的变量类型更改为 Drawable?
(带?)。