W3cubDocs

/Kotlin

chunkedSequence

Platform and version requirements: JVM (1.2), JS (1.2), Native (1.2)
fun CharSequence.chunkedSequence(size: Int): Sequence<String>

Splits this char sequence into a sequence of strings each not exceeding the given size.

The last string in the resulting sequence may have less characters than the given size.

import kotlin.test.*

fun main(args: Array<String>) {
//sampleStart
val words = "one two three four five six seven eight nine ten".split(' ')
val chunks = words.chunked(3)

println(chunks) // [[one, two, three], [four, five, six], [seven, eight, nine], [ten]]
//sampleEnd
}

Parameters

size - the number of elements to take in each string, must be positive and can be greater than the number of elements in this char sequence.

Platform and version requirements: JVM (1.2), JS (1.2), Native (1.2)
fun <R> CharSequence.chunkedSequence(
    size: Int, 
    transform: (CharSequence) -> R
): Sequence<R>

Splits this char sequence into several char sequences each not exceeding the given size and applies the given transform function to an each.

import kotlin.test.*

fun main(args: Array<String>) {
//sampleStart
val codonTable = mapOf("ATT" to "Isoleucine", "CAA" to "Glutamine", "CGC" to "Arginine", "GGC" to "Glycine")
val dnaFragment = "ATTCGCGGCCGCCAACGG"

val proteins = dnaFragment.chunkedSequence(3) { codon: CharSequence -> codonTable[codon.toString()] ?: error("Unknown codon") }

// sequence is evaluated lazily, so that unknown codon is not reached
println(proteins.take(5).toList()) // [Isoleucine, Arginine, Glycine, Arginine, Glutamine]
//sampleEnd
}

Parameters

size - the number of elements to take in each char sequence, must be positive and can be greater than the number of elements in this char sequence.

Return

sequence of results of the transform applied to an each char sequence.

Note that the char sequence passed to the transform function is ephemeral and is valid only inside that function. You should not store it or allow it to escape in some way, unless you made a snapshot of it. The last char sequence may have less characters than the given size.

© 2010–2019 JetBrains s.r.o.
Licensed under the Apache License, Version 2.0.
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/chunked-sequence.html