Search code examples
inheritancekotlinkotlin-interop

how to define class in kotlin with member can be accessed in java derived class


Having a class defined in kotlin, with members

@JvmField protected val clickHandler: BaseClickHandler
@JvmField protected var layoutId : Int

but when in java trying to extends this class and access the member it gets error.

interface ViewDelegate {

    fun onCreateViewHolder(parent: ViewGroup): RecyclerView.ViewHolder
    fun onBindViewHolder(holder: RecyclerView.ViewHolder, item: Data, position: Int)
}


open class ViewDelegateImp(@JvmField protected val clickHandler: BaseClickHandler) : ViewDelegate {

    @JvmField protected var layoutId = R.layout.default

    override fun onCreateViewHolder(parent: ViewGroup): RecyclerView.ViewHolder {
        return ItemViewHolder(parent.inflate(layoutId, false), clickHandler)
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, item: Data, position: Int) {
        (holder as? ItemViewHolder)?.bindView(item, position)
    }
}

//extension:
fun ViewGroup.inflate(layoutId: Int, attachToRoot: Boolean = false): View {
    return LayoutInflater.from(context).inflate(layoutId, this, attachToRoot)
}

in java want to derive from ViewDelegateImp, and override the var layoutId and the use the protected val clickHandler

class DerivedDelegateImp extends ViewDelegateImp {

    public DerivedDelegateImp(BaseClickHandler clickHandler) {
        super(clickHandler);
        layoutId = R.layout.derived;  // want to use different layout, but get error "cannot resolve layoutId"
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, Data item, int position) {
        super.onBindViewHolder(holder, item, position);
    }

    @NotNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent) {

        View vw = LayoutInflater.from(parent.getContext()).inflate(layoutId, parent, false);

        return new StoryItemViewHolder(vw, clickHandler); // here got error clickHandler has private access in ViewDelegateImp 

        //return super.onCreateViewHolder(parent);  //<== this is fine
    }
}

Solution

  • It must be the IDE issue, no matter what else (sync, clean, rebuild) tried it only works after delete the project and re clone to get a fresh code base and adding those code back.