Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 392
Entreco Avatar asked Aug 04 '17 20:08

Entreco


1 Answers

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.

like image 152
BladeCoder Avatar answered Oct 08 '22 07:10

BladeCoder