[每天一点编程技巧]Kotlin中使用Sequence取代递归

516 阅读1分钟

Kotlin标准库中提供一系列超函数

Sequnece是其中一个,类似Reduce

官方描述:

/**
 * Returns a sequence defined by the starting value [seed] and the function [nextFunction],
 * which is invoked to calculate the next value based on the previous one on each iteration.
 *
 * The sequence produces values until it encounters first `null` value.
 * If [seed] is `null`, an empty sequence is produced.
 *
 * The sequence can be iterated multiple times, each time starting with [seed].
 *
 * @see kotlin.sequences.sequence
 *
 * @sample samples.collections.Sequences.Building.generateSequenceWithSeed
 */
@kotlin.internal.LowPriorityInOverloadResolution
public fun <T : Any> generateSequence(seed: T?, nextFunction: (T) -> T?): Sequence<T> =
    if (seed == null)
        EmptySequence
    else
        GeneratorSequence({ seed }, nextFunction)

使用实例:

例如有下面一个递归调用,用于从Context中查询Activity

fun Context.findActivity(): Activity? {
    if (this is Activity) {
        return this
    } else if (this is ContextWrapper) {
        return this.baseContext.findActivity()
    }
    return null
}

使用Sequnce:

fun Context.findActivity() {
    generateSequence(this, {
        (it as? ContextWrapper)?.baseContext
    }).firstOrNull { 
        it is Activity
    }
}