TooLazy
TooLazy

Reputation: 906

Kotlin generics abstract class

I have an abstract class in Kotlin:

abstract class SimpleRecyclerAdapter<VH : SimpleRecyclerAdapter.Holder, D> constructor(
     context: Context, 
     var data: MutableList<D>
): RecyclerView.Adapter<VH>() {

    //inner class inside main
    abstract class Holder constructor(view: View) : RecyclerView.ViewHolder(view) {}
}

Everything work fine, but my inner class Holder does not see a D parameter of the outer class and data variable

If i mark Holder class as inner class like that:

abstract inner class Holder constructor(view: View) : RecyclerView.ViewHolder(view) {}

D parameter is visible for now, but here

SimpleRecyclerAdapter<VH : SimpleRecyclerAdapter.Holder, D>

im getting an error "2 type arguments expected for class..." and here RecyclerView.Adapter<VH> "expected RecyclerView.ViewHolder, found VH" - seems like VH is not visible. Where am i wrong? I need a D parameter inside an inner class, but with inner keyword its not working.

Upvotes: 1

Views: 478

Answers (1)

hotkey
hotkey

Reputation: 147901

To fix the error that you encounter when you add the inner modifier, you need to specify the type arguments for the outer class at the inner class' use sites:

abstract class SimpleRecyclerAdapter<VH : SimpleRecyclerAdapter<VH, D>.Holder, D> 
                                                               ^^^^^^^

And the complete code:

abstract class SimpleRecyclerAdapter<VH : SimpleRecyclerAdapter<VH, D>.Holder, D> (
    context: Context,
    var data: MutableList<D>
): RecyclerView.Adapter<VH>() {

    //inner class inside main
    abstract inner class Holder constructor(view: View) : RecyclerView.ViewHolder(view) {
        fun foo(d: D) = Unit // D is visible here
    }
}

Upvotes: 1

Related Questions