Chunked
It's very common to see this chunking logic in production code.
You have a huge list of identifiers that you read from somewhere and you need to check whether your database or some remote service contains them. But there are limitations on how many identifiers you can pass with a single request. Databases, for example, often have limitations of the number of arguments to a query and on the total query length:
fun dbCall(ids: List<Int>) { if (ids.size > 1000) { throw RuntimeException("Can't process more than 1000 ids") }
// Does something here }
We can't simply pass an entire list to our function:
// That will fail at runtime dbCall(hugeList)
So, we write large piles of imperative code:
val pageSize = 1000 val pages = hugeList.size / pageSize for (i in 0..pages) { val from = i * pageSize val p = (i+1) * pageSize val to = minOf(p, hugeList.size) dbCall(hugeList.slice(from until to)) }
Luckily, since Kotlin 1.2, there's the chunked()
function for that:
hugeList.chunked(pageSize...