Home > Mobile >  Inject sealed class with Hilt/Dagger2
Inject sealed class with Hilt/Dagger2

Time:06-10

I have to inject a sealed class through constructor, but I am receiving the compiling error:

  • Cannot be provided without an @Provides-annotated method

So, what I'm trying to do is to create a sealed like this:

sealed class Alphabet {
    object A: Alphabet()
    object B: Alphabet()
    data class C (val x: String): Alphabet()
    data class D (val y: Int): Alphabet()
}

And inject it in the constructor of another class like this:

@ViewModelScoped
class RandomUseCase @Inject constructor(
    private val alphabet: Alphabet
) {
    val z = when (alphabet) {
        A -> ...
        B -> ...
        C -> alphabet.x
        D -> alphabet.y
    }

So, how can I inject this?

CodePudding user response:

So, according to Kotlin official documentation Constructor of Sealed classes are private by default and Hilt needs a visible constructor to get its implementation from.

enter image description here

Suggestions:

Instead of injecting sealed class and using it in a function, you can simply pass a sealed class object in function and then compare it in function like this.

 fun sampleForSealed() {
    
    sampleForPassingSealed(Alphabet.A)
}

fun sampleForPassingSealed(alphabet: Alphabet) {
    when (alphabet) {
        Alphabet.A -> {

        }
        Alphabet.B -> {

        }
    }
}

Happy Coding!

CodePudding user response:

This thing does not make sense. Dagger will generate a code (so compile time) that will prepare some concrete implementation of Alphabet to be injected. But then you have a run time check with when. I just don't get it.

And let's say that the above makes sense. At the moment Dagger does not know how to find the implementation to be injected in the UseCase. You need to tell Dagger by using @Provides as part of a Dagger Module.

@Provides
fun provideAlphabet(): Alphabet {
         return B
}

But as you can see - always B will be injected in the UseCase so why using when?

  • Related