I have read the artical.
When you are initialising the ViewModel through ViewModelProviders without a factory, this means that you can only instantiate a ViewModel which has no constructor arguments.
The following code is from the project android-room-with-a-view
Why can the project create an instance of class ViewModel with constructor argument without a factory in Kotlin?
Code
wordViewModel = ViewModelProvider(this).get(WordViewModel::class.java)
class WordViewModel(application: Application) : AndroidViewModel(application) {
...
}
That answer has always been wrong. ViewModelProviders.of(this)
has always used at least AndroidViewModelFactory
, which supports the AndroidViewModel
class which allows automatically making an Application
class available as a constructor parameter.
Additionally, when using 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.