【发布时间】:2018-01-17 20:30:01
【问题描述】:
对于我当前的项目,我使用的是 Kotlin 和 Dagger 2。 我想在辅助构造函数中注入依赖项,但构造函数永远不会被初始化。
class SelectionFragmentModel ():ViewModel(){
lateinit var channelInfosRepository: ChannelInfosRepository
@Inject constructor(channelInfosRepository: ChannelInfosRepository) : this(){
this.channelInfosRepository = channelInfosRepository
}
...
}
作为一种解决方法,我目前正在注入主构造函数,但这不是最佳的。
class SelectionFragmentModel @Inject constructor(private val channelInfosRepository: ChannelInfosRepository):ViewModel(){
constructor() : this(ChannelInfosRepository())
...
}
我错过了什么吗?
【问题讨论】:
-
你的意思是没有参数的构造函数?
-
主构造函数应该没有参数,注入应该发生在辅助构造函数中
-
在
Kotlin中并非如此。从文档A class in Kotlin can have a primary constructor and one or more secondary constructors. The primary constructor is part of the class header: it goes after the class name (and optional type parameters)中检查这一点 -
@user3517658 有什么解决办法吗?
-
任何解决方案?