Home > Mobile >  How do I initialize 'inline' an array of arrays in Kotlin
How do I initialize 'inline' an array of arrays in Kotlin

Time:11-09

new bee in Kotlin and I am trying to compile a very simple thing. I'd like to initialize an array of lists with one line of code. But I get stuck in always have to uses mutable objects and inserts unto the list.

Here what I have which I don't like. It is too complicated and many lines of code, the array does not need to be mutable in reality. It will be always the same size and same number of elements.

val r0 = arrayListOf<Int>(1, 3, 5, 7)
val r1 = arrayListOf<Int>(10, 11, 16, 20)
val r2 = arrayListOf<Int>(23, 30, 34, 60)

val list: MutableList<ArrayList<Int>> = ArrayList()
list.add(r0)
list.add(r1)
list.add(r2)

That works, but I want something like

val list2: List<ArrayList<Int>> = ArrayList(
    arrayListOf<Int>(1, 3, 5, 7),
    arrayListOf<Int>(10, 11, 16, 20),
    arrayListOf<Int>(23, 30, 34, 60)
)

But this does not compile, not sure why.

thank you.

CodePudding user response:

Taking your original of:

val list2: List<ArrayList<Int>> = ArrayList(
    arrayListOf<Int>(1, 3, 5, 7),
    arrayListOf<Int>(10, 11, 16, 20),
    arrayListOf<Int>(23, 30, 34, 60)
)

I modified it to this, the kotlin constructors almost always follow arrayListOf nomenclature, and you had ArrayList on the first line after the =

val list2: ArrayList<ArrayList<Int>> = arrayListOf(
    arrayListOf(1, 3, 5, 7),
    arrayListOf(10, 11, 16, 20),
    arrayListOf(23, 30, 34, 60)
)

The types are not necessary on each internal list, since you've declared them at the variable

Other examples of constructors using this pattern:

listOf, mutableListOf, intArrayOf, booleanArrayOf

Some non similar constructors:

arrayOfNulls, emptyArray, emptyList

CodePudding user response:

Here's a simple way:

val list2: List<List<Int>> = listOf(
    listOf(1, 3, 5, 7),
    listOf(10, 11, 16, 20),
    listOf(23, 30, 34, 60)
)
  • Related