Search code examples
androidkotlinviewmodelandroid-architecture-components

Android ViewModelProviderFactory in kotlin


I'm experimenting with the Architecture Components from Google. Specifically I want to implement a ViewModelProvider.Factory to create a ViewModel that takes constructor parameters, like so:

class MyFactory(val handler: Handler) : ViewModelProvider.Factory {
    override fun <T : ViewModel?> create(modelClass: Class<T>?): T {
        return MyViewModel(handler) as T
    }
}

My ViewModel looks like this:

class MyViewModel(val handler: Handler) : ViewModel() 

Anyone knows how to avoid the nasty cast in the end :

return MyViewModel(handler) as T

Solution

  • You could write:

    class MyFactory(val handler: Handler) : ViewModelProvider.Factory {
        override fun <T : ViewModel> create(modelClass: Class<T>): T {
            return modelClass.getConstructor(Handler::class.java).newInstance(handler)
        }
    }
    

    This will work with any class accepting a Handler as constructor argument and will throw NoSuchMethodException if the class doesn't have the proper constructor.