简体   繁体   English

使用 Hilt/Dagger2 注入密封类

[英]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没有@Provides-annotated 方法就无法提供

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?那么,我该如何注入呢?

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.因此,根据 Kotlin 官方文档,密封类的构造函数默认是私有的,Hilt 需要一个可见的构造函数来获取其实现。

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.注入类或实现的目的是获取每个实例化的对象,但在密封类的情况下,您不能直接在其 Hilt 模块中实例化密封类,如下所示。

@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!快乐编码!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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