添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
@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)
    Enter fullscreen mode
    Exit fullscreen mode

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 {}
    Enter fullscreen mode
    Exit fullscreen mode

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 {
    return classType.getDeclaredConstructor().newInstance()
    Enter fullscreen mode
    Exit fullscreen mode

You cannot use T::class.java directly, thus you need to pass in as Class<T> parameter into the viewModel() function.

This limitation is called Type erasure because the JVM platform doesn't support generic types. The generic type is lost when we compile Kotlin to JVM bytecode.

However, Kotlin overcomes this limitation with Reified type parameter.

inline fun <reified T> viewModel(): T {
    return (T::class.java).getDeclaredConstructor().newInstance()
    Enter fullscreen mode
    Exit fullscreen mode

With reified T, you can access the class type (i.e.T::class.java) and you don't need to pass it in as in the previous example.

To create a view model, you call viewModel<MyViewModel>()

val viewModel = viewModel<MyViewModel>()
    Enter fullscreen mode
    Exit fullscreen mode
              Simplify ViewModelProvider.Factory() Implementation with Kotlin Lambda and Object Expressions
                  #android
                  #kotlin
                  #beginners
      

Built on Forem — the open source software that powers DEV and other inclusive communities.

Made with love and Ruby on Rails. DEV Community © 2016 - 2024.