HomeAndroidWhat's Kotlin Reified Sort Parameter?

What’s Kotlin Reified Sort Parameter?


One of the vital widespread makes use of of this reified sort parameter is view mannequin creation. For instance, the next code is the viewModels() composable helper perform to create the view mannequin.

@Composable
public inline enjoyable <reified VM : ViewModel> viewModel(
    viewModelStoreOwner: ViewModelStoreOwner 
        = checkNotNull(LocalViewModelStoreOwner.present) {
        "No ViewModelStoreOwner was offered by way of LocalViewModelStoreOwner"
    },
    key: String? = null,
    manufacturing unit: ViewModelProvider.Manufacturing unit? = null
): VM = viewModel(VM::class.java, viewModelStoreOwner, key, manufacturing unit)

It has 3 parameters, and it calls one other viewModel(), however let’s simplify this view mannequin creation for the sake of understanding this reified.

Assuming you might have

class MyViewModel {}

Class Sort Parameter

and also you wish to create an occasion of MyViewModel by its class sort (i.e. MyViewModel::Class.java), you wish to name (MyViewModel::class.java).getDeclaredConstructor().newInstance(). To make it a helper perform, you create the next:

enjoyable <T>viewModel(classType: Class<T>): T {
    return classType.getDeclaredConstructor().newInstance()
}

To create the view mannequin, you name viewModel(MyViewModel::class.java)

val viewModel = viewModel(MyViewModel::class.java)

You can not use T::class.java immediately, thus you could cross in as Class<T> parameter into the viewModel() perform.

This limitation is known as Sort erasure as a result of the JVM platform does not assist generic varieties. The generic sort is misplaced once we compile Kotlin to JVM bytecode.

Nonetheless, Kotlin overcomes this limitation with Reified sort parameter.

Reified Sort Parameter

As a substitute of utilizing the category sort parameter above, you should utilize the reified sort parameter. So you modify the viewModel() helper perform to the next.

inline enjoyable <reified T> viewModel(): T {
    return (T::class.java).getDeclaredConstructor().newInstance()
}

Please word that you have to specify the inline.

With reified T, you’ll be able to entry the category sort (i.e.T::class.java) and also you need not cross it in as within the earlier instance.

To create a view mannequin, you name viewModel<MyViewModel>()

val viewModel = viewModel<MyViewModel>()

or you may also name viewModel() route with out passing the category title, however you could declare the viewModel variable sort which permits the Kotlin compiler to deduce it.

val viewModel: MyViewModel = viewModel()

Conclusion

Inline reified sort parameter is one other fancy approach of passing class sort(i.e. Class<T>) in your perform. The caller now not must explicitly cross within the class sort parameter anymore right into a perform.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments