Jisip
Jisip

Reputation: 445

How to create variables in a for-loop with Kotlin

Given a maximum list size in parameter size and total amount of elements in parameter elements, I need to create a list of lists. What is the syntax for creating variables in for loops in Kotlin?

The way I'm thinking of going about this is to declare and create lists before elements are added to a list. Then, when a list has reached full capacity, it is switched out for the next list that is empty.

Here is the half-baked code:

fun listOfLists(size: Int, vararg elements: String): List<List<String>> {
    var amountOfElements = elements.size
    var currentSubList: List<String> = mutableListOf<String>()
    val numberOfLists: Int = amountOfElements / size + 1

    for (n in 0..numberOfLists) {
        // Code for creating the total number of lists needed
    }

    for (e in elements) {
        if (amountOfElements % size == 0) {
            // Code for switching lists
        }
        amountOfElements--
    }

Upvotes: 1

Views: 2028

Answers (1)

Alexey Soshin
Alexey Soshin

Reputation: 17711

As @dyukha correctly mentioned, what you need is chunked() function.

fun listOfLists(size: Int, vararg elements: String) = 
   elements.asList().chunked(size)

Or, if you want to be really efficient, you can also use asSequence():

fun listOfLists(size: Int, vararg elements: String) =
    elements.asSequence().chunked(size)

chunked() doesn't work on Array, because it's defined on Iterable and Sequence, and Array doesn't implement any of them.

Upvotes: 2

Related Questions