Search code examples
androidkotlindagger-2daggerdagger-hilt

Inject sealed class with Hilt/Dagger2


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?


Solution

  • 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.

    Link for reference here:

    And by reading you question i am really not sure why do you need a sealed class here. The purpose of injecting a class or a implementation is to get a per-instantiated object but in case of sealed class you can't directly instantiate sealed class in its Hilt module like below.

    @Singleton
    @Binds
    abstract fun provideAlphabet(alphabet: Alphabet): Alphabet
    

    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!