0

let's say I have a list defined in Kotlin:

val mylist = mutableListOf<List<Int>>(listOf(2,3,5), listOf(2,5,6))

Now, I want to assign a certain value to one of these sublists. For example, now that I have a list of

((2,3,5)(2,5,6))

I would like my list to be

((2,3,5)(2,100,6))

I'm used to doing this in Python by something like myList[1][1] = 100. How do I achieve the same result in Kotlin?

1 Answer 1

2

Kotlin has two sets of collection interfaces, the regular List, Set, etc. which are read-only, and the same ones with the Mutable prefix, which can be modified.

listOf will give you a List instance, while mutableListOf gives you a MutableList instance. If you use the latter for creating your nested lists, you can use the exact syntax you've asked about:

val mylist: MutableList<MutableList<Int>> = mutableListOf(mutableListOf(2,3,5), mutableListOf(2,5,6))

mylist[1][1] = 100

println(mylist) // [[2, 3, 5], [2, 100, 6]]

(I've added the explicit type for myList for clarity's sake, it can be omitted from the left side of the assignment.)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.