注入密封的班级/匕首2
我必须通过构造函数注入密封的类,但是我正在收到编译错误:
- 没有 @提供 @提供的方法,就无法提供,
因此,我要做的就是创建像这样的密封:
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
因此,根据Kotlin的官方文档构造函数,默认情况下是私人的,刀柄需要可见的构造函数才能从中获得其实施。
在此处参考:
通过阅读您的问题,我真的不确定为什么在这里需要密封的课程。注入类或实现的目的是获取人均对象,但如果是密封类,则不能直接在其刀柄模块中直接实例化密封类。
建议:
,而不是注入密封类并将其用于函数中,您可以简单地将密封的类对象传递到函数中,然后在函数中进行比较。
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.
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.