5

I want to know how to make a resizeable two-dimensional array in Kotlin.

C++ example: vector< vector<int> > my_vector

What I've tried: var seqList: List<List<Int>> = ArrayList<ArrayList<Int>>()

but I'm getting an error when using seqList.add()

error: unresolved reference: add

I have read some questions regarding 2d arrays in Kotlin at stackoverflow, but they are about not-resizeable arrays or are outdated

Subhanshuja
  • 390
  • 1
  • 3
  • 20
Misho Tek
  • 624
  • 2
  • 11
  • 22

1 Answers1

7

Kotlin has separate List and MutableList interfaces, as explained here, for example. ArrayList is a MutableList, you just have to save it as a MutableList variable in order to be able to access methods that mutate it:

val seqList: MutableList<MutableList<Int>> = ArrayList() // alternatively: = mutableListOf()

seqList.add(mutableListOf<Int>(1, 2, 3))

Also note the mutableListOf and arrayListOf methods in the standard library, which are handy for creating lists instead of directly using the constructor of, say, ArrayList.

zsmb13
  • 85,752
  • 11
  • 221
  • 226
  • 1
    I've pasted your code and run it, but I'm getting "Error:(6, 50) Kotlin: Type mismatch: inferred type is ArrayList> but MutableList> was expected" – Misho Tek Nov 18 '17 at 16:54
  • 3
    Since `MutableList` is in variant on `T`, `MutableList>` is not assignable to `MutableList>`, neither is `ArrayList>`. Instead, use `ArrayList>()` on the right hand side, or omit the type argument to make the compiler infer it: just `ArrayList()` – hotkey Nov 18 '17 at 17:30
  • 2
    Oops, my bad, should've tried running the code. You can do what @hotkey suggested, I'll update my answer. – zsmb13 Nov 18 '17 at 17:47
  • 2
    I'd like to add that there's another function in the standard library since Kotlin 1.1 which might be useful here: the factory function [`MutableList(n) { ... }`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-mutable-list.html) – hotkey Mar 14 '18 at 12:59