chunkedSequence所在位置是kotlin.text.chunkedSequence,其相關用法介紹如下。

用法一

fun CharSequence.chunkedSequence(size: Int): Sequence<String>

將此字符序列拆分為字符串序列,每個字符串不超過給定的 size

結果序列中的最後一個字符串的字符數可能少於給定的 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
}

輸出:

[[one, two, three], [four, five, six], [seven, eight, nine], [ten]]

參數

size- 每個字符串中的元素數,必須為正數,並且可以大於此字符序列中的元素數。

用法二

fun <R> CharSequence.chunkedSequence(
    size: Int, 
    transform: (CharSequence) -> R
): Sequence<R>

將此字符序列拆分為多個字符序列,每個字符序列不超過給定的size,並將給定的transform 函數應用於每個。

例子:

import java.util.Locale
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
}

輸出:

[Isoleucine, Arginine, Glycine, Arginine, Glutamine]

參數

size- 每個 char 序列中的元素數,必須為正數,並且可以大於此 char 序列中的元素數。

返回

transform 的結果序列應用於每個字符序列。

請注意,傳遞給transform 函數的字符序列是短暫的,僅在該函數內部有效。您不應該存儲它或讓它以某種方式逃逸,除非您製作了它的快照。最後一個字符序列的字符數可能少於給定的 size