为什么有些人将@Inject用于类的构造函数,而另一些人却不将此注释用于构造函数。 可以使用此选项吗?
答案 0 :(得分:0)
如果您自己提供实例,则不需要:
//without @Inject
class SomeInstance contructor(...): SomeInstanceInterface{}
@Module
class Module{
@Provides()
fun provide():SomeInstanceInterface {
return SomeInstance(...)
}
}
但是,如果您希望Dagger为您创建实例,则需要用@Inject
标记构造函数,并要求Dagger
创建实例:
@Module
class Module{
@Provides()
fun provide(inst: SomeInstance):SomeInstanceInterface = inst
}
或
@Component
interface Component{
fun someInstance():SomeInstanceInterface
}