how i can use ListOfArrays in Kotlin

Issue

I have been working mainly in JAVA but now I need to program some small things in kotlin. Among other things I am trying to convert the result of a database query into a list of array. The result of the database query has 4 columns, the number of rows I can not predict.

I have tried the following:

var output: mutableList<List<String>>
var output  mutableListOf<String>()
var output  mutableListOf<ArrayList>
List<List<String>> listOfLists  new ArrayList<List<String>>()

What I would like to do is this:

output.add(arrayOf("Field1", "Filed2", "Field3", "Field4"))

It can’t be that hard, can it?

Solution

In kotlin you should use lists where you can. What you are trying to create is:

    val output  mutableListOf<List<String>>()
    output.add(listOf("Field1", "Filed2", "Field3", "Field4"))

If you are iterating through some other list to create your data for output you could do something like:

    val otherList  listOf<String>("a", "b", "v")
    val output  otherList.map { otherListData ->
        listOf(otherListData + 1, otherListData + 2, otherListData + 3, otherListData + 4)
    }

In which case you would only have immutable lists.

Answered By – Милош Којадиновић

Leave a Comment