Husker
Husker

Reputation: 81

how i can use ListOfArrays in Kotlin

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?

Upvotes: 1

Views: 111

Answers (2)

Joffrey
Joffrey

Reputation: 37660

A list of arrays can be expressed as List<Array<T>>.

So if you want a mutable list to which you can add arrays of strings, simply do:

var output = mutableListOf<Array<String>>()
output.add(arrayOf("Field1", "Filed2", "Field3", "Field4"))

That being said, why do you want to use arrays? It's generally more convenient to work with lists, unless you're constrained by another API.

Upvotes: 2

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.

Upvotes: 0

Related Questions