我在带有 HILT 的多模块 android 项目中面临这个问题。
kotlin.UninitializedPropertyAccessException: lateinit property repository has not been initialized in MyViewModel
我的模块是
- 应用模块
- 视图模型模块
- 用例模块
- 数据源模块
'应用模块'
@AndroidEntryPoint
class MainFragment : Fragment() {
private lateinit var viewModel: MainViewModel
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View {
return inflater.inflate(R.layout.main_fragment, container, false)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
viewModel = ViewModelProviders.of(this).get(MainViewModel::class.java)
viewModel.test()
}}
'视图模型模块'
class MainViewModel @ViewModelInject constructor(private val repository: MyUsecase): ViewModel() {
fun test(){
repository.test()
}}
'用例模块'
class MyUsecase @Inject constructor() {
@Inject
lateinit var feature: Feature
fun doThing() {
feature.doThing()
}
@Module
@InstallIn(ApplicationComponent::class)
object FeatureModule {
@Provides
fun feature(realFeature: RealFeature): Feature = realFeature
}
}
'数据源模块'
interface Feature {
fun doThing()
}
class RealFeature : Feature {
override fun doThing() {
Log.v("Feature", "Doing the thing!")
}
}
依赖项是
MyFragment ---> MyViewModel ---> MyUseCase ---> DataSource
我对这段代码做错了什么,请纠正它。