从Kotlin的`buildSequence`返回

时间:2018-05-21 19:38:25

标签: kotlin coroutine

我在Kotlin中使用buildSequence功能。如何在函数中间结束迭代?我正在寻找类似于C#的yield break陈述的东西。

我的代码如下所示。我被困在TODO

fun foo(list:List<Number>): Sequence<Number> = buildSequence {
    if (someCondition) {
        // TODO: Bail out early with an empty sequence
        // return doesn't seem to work....
    }

    list.forEach {
        yield(someProcessing(it))
    }
}

修改

显然,我误解了消息来源。问题不是从buildSequence函数返回。以下适用于我:

fun foo(list:List<Number>): Sequence<Number> = buildSequence {
    return@buildSequence

    list.forEach {
        yield(someProcessing(it))
    }
}

编辑2

问题是我将return放在一个本地帮助函数中,该函数验证buildSequence中多个点的数据(因此是辅助函数)。显然我无法从辅助函数中的buildSequence返回。错误消息并不是非常有用......

2 个答案:

答案 0 :(得分:2)

只需使用return@buildSequence labeled return from lambda,而未标记的return则表示从foo&#39;返回

另请参阅:Whats does “return@” mean?

答案 1 :(得分:0)

自Kotlin v 1.3.x以来,首选序列语法已更改。 ({buildSequencekotlin.sequences.sequence取代)

更新了1.3.x版Kotlin的“从生成器中提前返回”代码段(包括try-catch== null早期返回示例):

// gen@ is just a subjective name i gave to the code block.
// could be `anything@` you want
// Use of named returns prevents "'return' is not allowed here" errors.
private fun getItems() = sequence<Item> gen@ {

    val cursor: Cursor?
    try {
        cursor = contentResolver.query(uri,*args)
    } catch (e: SecurityException) {
        Log.w(APP_NAME, "Permission is not granted.")
        return@gen
    }

    if (cursor == null) {
        Log.w(APP_NAME, "Query returned nothing.")
        return@gen
    }

    // `.use` auto-closes Closeable. recommend.
    // https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.io/use.html 
    cursor.use {
        // iterate over cursor to step through the yielded records
        while (cursor.moveToNext()) {
            yield(Item.Factory.fromCursor(cursor))
        }
    }
}

(感谢所有以前帮助我进入“命名回报”轨道的帖子。)