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

用法一

fun <T> Sequence<T>.zipWithNext(): Sequence<Pair<T, T>>

返回此序列中每兩個相鄰元素的對序列。

如果此序列包含少於兩個元素,則返回的序列為空。

操作是 intermediatestateless

例子:

import kotlin.test.*

fun main(args: Array<String>) {
//sampleStart
val letters = ('a'..'f').toList()
val pairs = letters.zipWithNext()

println(letters) // [a, b, c, d, e, f]
println(pairs) // [(a, b), (b, c), (c, d), (d, e), (e, f)]
//sampleEnd
}

輸出:

[a, b, c, d, e, f]
[(a, b), (b, c), (c, d), (d, e), (e, f)]

用法二

fun <T, R> Sequence<T>.zipWithNext(
    transform: (a: T, b: T) -> R
): Sequence<R>

返回一個序列,其中包含將給定的transform 函數應用於該序列中每對兩個相鄰元素的結果。

如果此序列包含少於兩個元素,則返回的序列為空。

操作是 intermediatestateless

例子:

import kotlin.test.*

fun main(args: Array<String>) {
//sampleStart
val values = listOf(1, 4, 9, 16, 25, 36)
val deltas = values.zipWithNext { a, b -> b - a }

println(deltas) // [3, 5, 7, 9, 11]
//sampleEnd
}

輸出:

[3, 5, 7, 9, 11]