Jetpack Compose and ViewModel-Instantiation


What does the following line of code do?

fun NotesApp(noteViewModel: NoteViewModel = viewModel()) {

The default parameter confuses me. The class, which inherits from ViewModel, is called NoteViewModel.
Wouldn’t the default parameter be: NoteViewModel()?

But it works nevertheless. How is that possible?


It is the default initializer for view models inside a Composable. It takes in a type parameter, so I don’t think what you’ve posted above would be enough.

For example, if you wanted to initialise a MainViewModel, it’ll be something like

val vm = viewModel<MainViewModel>()

It is supposed to return the same instance of a viewmodel, if it had been created in the past.

Answered By – Richard Onslow Roper

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published