import kotlin.random.Random fun Iterable.splitAt(n: Int): Pair, List> = if (this is List) { val end = n.coerceAtMost(size) subList(0, end) to subList(end, size) } else { take(n) to drop(n) } fun Iterable.chunks(sizes: Sequence): Sequence> = sizes .runningFold(emptyList() to this) { (_, list), size -> list.splitAt(size) } .drop(1) .map { it.first } .takeWhile { it.isNotEmpty() } fun main() { (0..10).chunks(generateSequence { Random.nextInt(1, 5) }).forEach(::println) }