I am trying to write a generic base activity, that specifies it's ViewModel type a generic parameter:
abstract class BaseActivity<T : ViewModel> : AppCompatActivity()
Now I am trying to write a lazy initialized property for my ViewModel:
val viewModel by lazy { ViewModelProviders.of(this, getFactory()).get(T) }
The error that is displayed is Type Parameter T is not an expression
Also using ::class
or ::class.java
did not help. Can anyone explain the problem?
EDIT: I tried to use a reified inline function like this:
inline fun <reified T : ViewModel?> AppCompatActivity.obtainViewModel(factory: ViewModelProvider.Factory): T {
return ViewModelProviders.of(this, factory).get(T::class.java)
}
And used it like this:
abstract class BaseActivity<T> : AppCompatActivity() {
val viewModel by lazy { obtainViewModel<T>(getFactory())
}
Now I get the error, that T cannot be used as a reified parameter.
EDIT2: The best solution so far seems to be this: Link, but its overhead to implement the abstract token in every extending class.