1

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

Toni Joe
  • 7,715
  • 12
  • 50
  • 69

1 Answers1

2

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 ?).

Garnik
  • 145
  • 6
  • Yes but `ContextCompat.getDrawable()` returns a nullable type and if I change the variable type to nullable like this `@Inject lateinit var logo: Drawable?`, it throws an error and that is the issue – Toni Joe Mar 23 '20 at 13:37
  • Because `lateinit` modifier is not allowed on properties of nullable types. So, you must remove it too. – Garnik Mar 23 '20 at 14:05
  • I tried this `@Inject var logo: Drawable? = null` but then I got another error `error: Dagger does not support injection into private fields` – Toni Joe Mar 23 '20 at 14:43
  • 1
    Try `@set:Inject` instead of `@Inject`. – Garnik Mar 23 '20 at 15:01