Kotlin中通用类类型的用法 [英] Generic class type usage in Kotlin
问题描述
我正在尝试编写一个通用基本活动,该活动指定其ViewModel类型为通用参数:
I am trying to write a generic base activity, that specifies it's ViewModel type a generic parameter:
abstract class BaseActivity<T : ViewModel> : AppCompatActivity()
现在,我正在尝试为ViewModel编写一个惰性的初始化属性:
Now I am trying to write a lazy initialized property for my ViewModel:
val viewModel by lazy { ViewModelProviders.of(this, getFactory()).get(T) }
显示的错误是Type Parameter T is not an expression
也使用::class
或::class.java
并没有帮助.谁能解释这个问题?
Also using ::class
or ::class.java
did not help. Can anyone explain the problem?
编辑:我试图使用这样的标准化内联函数:
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)
}
并像这样使用它:
abstract class BaseActivity<T> : AppCompatActivity() {
val viewModel by lazy { obtainViewModel<T>(getFactory())
}
现在我得到了一个错误,即T不能用作化参数.
Now I get the error, that T cannot be used as a reified parameter.
The best solution so far seems to be this: Link, but its overhead to implement the abstract token in every extending class.
推荐答案
您的类具有类型参数T
,不幸的是,该参数在运行时被擦除.结果,调用get(T)
不起作用(我猜该方法实际上期望使用Class
吗?).
Your class has a type parameter T
, which unfortunately gets erased at runtime. As a result, the call get(T)
does not work (I guess the method expects a Class
actually?).
您似乎已经注意到了这一点,因此尝试通过将处理封装到使用reified
类型的方法中来对其进行修复.但是,您不能将T
作为固定参数传递,因为在调用reified
类型的方法时,该类型已经被擦除.结果,obtainViewModel<T>
也将不起作用.您可以做的是对常规泛型方法使用T
,下面将进行演示:
You seem to have already noticed that and thus tried to fix it with encapsulating the handling into a method using reified
type. Yet, you cannot pass T
as a reified parameter since this type will already be erased when the reified
-typed method is called. As a result, obtainViewModel<T>
will not work either. What you can do, is using T
for ordinary generic methods, which the following demonstrates:
class Typed<T> {
val lazyProp by lazy {
listOf<T>()
}
}
这篇关于Kotlin中通用类类型的用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!