Reputation: 137
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
Reputation: 1525
Try this:
val lift: MutableList<MutableList<Any>> = mutableListOf<MutableList<Any>>(mutableListOf<Any>(),mutableListOf<Any>())
Upvotes: 1
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