简体   繁体   中英

How to override properties of java classes in Kotlin?

Somewhere in Java code there is a class 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 . And I want to create a generic class ViewHolder<V> like this:

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.

What I want here is to make the itemView property of MyViewHolder class to be of type V , not View . So for instance, MyViewHolder(TextView(context)).itemView would be a TextView . Is there any way to achieve this?

The Java class in your example has a field, not a property. 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM