为什么项目可以在没有工厂的情况下使用构造函数参数创建 class ViewModel 的实例

Why can the project create an instance of class ViewModel with constructor argument without a factory

我已阅读artical

当您在没有工厂的情况下通过 ViewModelProviders 初始化 ViewModel 时,这意味着您只能实例化一个没有构造函数参数的 ViewModel。

以下代码来自项目android-room-with-a-view

为什么项目可以在 Kotlin 中没有工厂的情况下使用构造函数参数创建 class ViewModel 的实例?

代码

wordViewModel = ViewModelProvider(this).get(WordViewModel::class.java)


class WordViewModel(application: Application) : AndroidViewModel(application) {

   ...
}

那个答案一直是错误的。 ViewModelProviders.of(this) 始终至少使用 AndroidViewModelFactory,它支持 AndroidViewModel class,它允许自动使 Application class 可用作构造函数参数。

此外,当使用 Fragment 1.2.0 or higher, the default factory has been updated to SavedStateViewModelFactory to also support using SavedStateHandle as a constructor parameter as per the Saved State module with ViewModel guide 时。