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
T extends ViewModel
but you give aMyViewModel
. when the client code use a specific type ofT
you always got aClassCastException
, e.g:val model:T = factory.create(T::class.java)
– GerstnerViewModel
or use the 3rd IoC container to create theViewModel
. – Gerstner