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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With