代码之家  ›  专栏  ›  技术社区  ›  Mashmagar

从Kotlin中的“buildSequence”返回

  •  0
  • Mashmagar  · 技术社区  · 8 年前

    我用的是 buildSequence 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))
        }
    }
    

    显然,我误诊了源头。这个问题不会再从 构建序列 功能。以下是我的作品:

    fun foo(list:List<Number>): Sequence<Number> = buildSequence {
        return@buildSequence
    
        list.forEach {
            yield(someProcessing(it))
        }
    }
    

    编辑2

    问题是我把 return 在本地助手函数中,该函数在 构建序列 构建序列 在helper函数中。错误消息没有太大帮助。。。

    1 回复  |  直到 8 年前
        1
  •  2
  •   hotkey    8 年前

    只是使用 return@buildSequence ,这是一个 labeled return from lambda 返回 意思是“从函数中返回” foo '.

    Whats does “return@” mean?

        2
  •  0
  •   ddotsenko    6 年前

    由于kotlinv1.3.x首选序列语法发生了变化。 ( buildSequence kotlin.sequences.sequence )

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

    // 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))
            }
        }
    }
    

    (之前所有帮助我进入“命名返回”轨道的帖子,请点击Thx。)