[英]How to override properties of java classes in Kotlin?
Somewhere in Java code there is a class ViewHolder
: Java代码中的某个地方有一个ViewHolder
类:
public static abstract class ViewHolder {
public final View itemView;
public ViewHolder(View itemView) { this.itemView = itemView; }
....
}
So in Kotlin instances of this class contain a read-only property itemView
of type View
. 因此,在Kotlin中,此类的实例包含View
类型的只读属性itemView
。 And I want to create a generic class ViewHolder<V>
like this: 我想创建一个通用类ViewHolder<V>
如下所示:
class MyViewHolder<V : View>(itemView: V) : ViewHolder(itemView) {
override val itemView = super.itemView as V // error: itemView overrides nothing
}
And if I remove the override
modifier the class compiles OK, but when I try to use the itemView
field I get the Overload resolution ambiguity
error. 而且,如果我删除了override
修饰符,则该类将编译为OK,但是当我尝试使用itemView
字段时,会出现Overload resolution ambiguity
错误。
What I want here is to make the itemView
property of MyViewHolder
class to be of type V
, not View
. 我想在这里是使itemView
的属性MyViewHolder
类为类型V
,不View
。 So for instance, MyViewHolder(TextView(context)).itemView
would be a TextView
. 因此,例如, MyViewHolder(TextView(context)).itemView
将是TextView
。 Is there any way to achieve this? 有什么办法可以做到这一点?
The Java class in your example has a field, not a property. 您的示例中的Java类具有一个字段,而不是一个属性。 Code that accesses a field in Java always refers to a specific class name, and it's not possible to override the field in another class, either in Java or in Kotlin. 访问Java中的字段的代码始终引用特定的类名,并且无法覆盖Java或Kotlin中另一个类中的字段。
You can create your own property, with a different name, that would return the value of the field cast to the type that you need. 您可以使用不同的名称创建自己的属性,该属性将把字段的值返回为所需的类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.