HappyProgrammer
HappyProgrammer

Reputation: 3

Define MutableList of an object

I have this block of code:

val page = object : AbstractViewRenderer(this, R.layout.pdf_page) {
    private var title: String? = null

    override fun initView(view: View) {}
}

Now I want to make a mutable list of object : AbstractViewRenderer(this, R.layout.pdf_page).

I mean something like this:

val page[] : MutableList<object : AbstractViewRenderer> = ...

How to do it? What should I use?

Upvotes: 0

Views: 753

Answers (1)

zsmb13
zsmb13

Reputation: 89668

Using an object expression creates a one-time, anonymous instance. If you want to reuse the logic inside it, create a class for it, something like this:

class MyViewRenderer(ctx: Context, layoutResId: Int) : AbstractViewRenderer(ctx, layoutResId) {
    private var title: String? = null

    override fun initView(view: View) {}
}

Then you can create instances or lists of instances of that class:

val page = MyViewRenderer(this, R.layout.pdf_page)

val pages: MutableList<AbstractViewRenderer> = mutableListOf(
        MyViewRenderer(this, R.layout.pdf_page),
        MyViewRenderer(this, R.layout.pdf_page),
        MyViewRenderer(this, R.layout.pdf_page)
)

Upvotes: 1

Related Questions