What is Kotlin Reified Type Parameter?
Simple example to understand reified type parameters in Kotlin
2 min readMar 24, 2023
One of the most common uses of this reified
type parameter is view model creation. For example, the following code is the viewModels()
composable helper function to create the view model.
@Composable
public inline fun <reified VM : ViewModel> viewModel(
viewModelStoreOwner: ViewModelStoreOwner
= checkNotNull(LocalViewModelStoreOwner.current) {
"No ViewModelStoreOwner was provided via LocalViewModelStoreOwner"
},
key: String? = null,
factory: ViewModelProvider.Factory? = null
): VM = viewModel(VM::class.java, viewModelStoreOwner, key, factory)
It has 3 parameters, and it calls another viewModel()
, but let's simplify this view model creation for the sake of understanding this reified
.
Assuming you have
class MyViewModel {}
Class Type Parameter
and you want to create an instance of MyViewModel
by its class type (i.e. MyViewModel::Class.java
), you want to call (MyViewModel::class.java).getDeclaredConstructor().newInstance()
.
To make it a helper function, you create the following:
fun <T>viewModel(classType: Class<T>): T {…