注入密封的班级/匕首2

发布于 2025-02-06 02:36:19 字数 667 浏览 2 评论 0原文

我必须通过构造函数注入密封的类,但是我正在收到编译错误:

  • 没有 @提供 @提供的方法,就无法提供,

因此,我要做的就是创建像这样的密封:

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

并将其注入这样的另一类的构造函数:

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

那么,我该如何注入?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

狼性发作 2025-02-13 02:36:20

因此,根据Kotlin的官方文档构造函数,默认情况下是私人的,刀柄需要可见的构造函数才能从中获得其实施。

在此处参考:

通过阅读您的问题,我真的不确定为什么在这里需要密封的课程。注入类或实现的目的是获取人均对象,但如果是密封类,则不能直接在其刀柄模块中直接实例化密封类。

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

建议:

,而不是注入密封类并将其用于函数中,您可以简单地将密封的类对象传递到函数中,然后在函数中进行比较。

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

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

        }
        Alphabet.B -> {

        }
    }
}

快乐编码!

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!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文