B.Thushar Marvel
B.Thushar Marvel

Reputation: 137

How to append list inside list in kotlin

I have created an empty lists using

var lift = mutableListOf<Any(mutableListOf<Any(),mutableListOf<Any>())

But

lift[0].add(1)

Gives me error. How to add elements to list inside list

Upvotes: 0

Views: 267

Answers (2)

MehranB
MehranB

Reputation: 1525

Try this:

val lift: MutableList<MutableList<Any>> = mutableListOf<MutableList<Any>>(mutableListOf<Any>(),mutableListOf<Any>()) 

Upvotes: 1

Tenfour04
Tenfour04

Reputation: 93609

The problem is that you have upcast the list type to Any instead of MutableList<Any>.

If you just typed:

mutableListOf(mutableListOf<Any>(),mutableListOf<Any>()) 

the type of items in the list is implicitly MutableList<Any>. But since you added <Any> like this:

mutableListOf<Any>(mutableListOf<Any>(),mutableListOf<Any>()) 

the compiler treats retrieved items as type Any instead of the specific type MutableList<Any> so you can't call functions on them.

You could also explicitly state the type like this, but it is not necessary:

mutableListOf<MutableList<Any>>(mutableListOf<Any>(),mutableListOf<Any>()) 

Upvotes: 4

Related Questions