简体   繁体   中英

How to filed inject a nullable type in an activity with dagger 2 and kotlin

I have a this dependency that I want to inject in some activity. I'm using dagger.android and did all the setup and the project compiles perfectly

In the AppModule:

 @Provides
 fun provideAppDrawable(application: Application): Drawable? {
    return ContextCompat.getDrawable(application, R.drawable.logo)
 }

In the activity:

@Inject lateinit var logo: Drawable

Now when I try to run the app, Dagger 2 throws this error error: [Dagger/Nullable] android.graphics.drawable.Drawable is not nullable

Is there a way to fix this problem? Thanks

This is about Null Safety in kotlin. From 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

So, you must either provide Drawable (without ?), or change your variable type in activity to Drawable? (with ?).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM