Reputation: 43
I have to inject a sealed class through constructor, but I am receiving the compiling error:
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?
Upvotes: 0
Views: 963
Reputation: 1010
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.
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
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!
Upvotes: 1