【问题标题】:Break out of an anonymous function in kotlin在 kotlin 中突破匿名函数
【发布时间】:2018-01-27 16:52:36
【问题描述】:

创建了一个测试用例来尝试并代表我正在尝试做的事情。我不知道如何“停止”继续在匿名函数内部工作。在下面的示例中,如果答案正确,我想跳出“苹果”部分。下面的代码无法编译,因为它说 return@apple 而不是 return@banana 这是唯一有效的选项,但我在下面写它是为了解释我想要实现的目标并更好地理解如何去做类似的事情这个。

class FunctionBreakingTest {
    @Test fun stopInMiddleOfLambda() {
        var answer = "wrong"
        doStuff apple@ {
            doStuff banana@ {
                answer = "correct"
                if (answer == "correct") {
                    return@apple
                }
                answer = "wrong"
            }

            answer = "wrong"
        }

        assertEquals("correct", answer)
    }

    private fun doStuff(foo: () -> Unit) = foo.invoke()
}

【问题讨论】:

    标签: loops return kotlin


    【解决方案1】:

    您需要将doStuff 设为inline 函数:non-local return 仅支持内联的 lambda。

    private inline fun doStuff(foo: () -> Unit) = foo.invoke()
    

    那么你的测试用例就通过了。

    【讨论】:

      【解决方案2】:

      不仅return@apple非法,简单的return也是非法的(因为非本地返回需要内联 - 请参阅@hotkey的答案,将doStuff内联然后它可以工作)......

      (请注意,只有传递给内联函数的 lambda 表达式才支持这种非本地返回。)

      This section of the Kotlin Documentation 覆盖标签处的退货。注意:使用匿名函数而不是 lambda 可以让您根据需要消除标签(但是,您只能获得本地返回,并且您需要稍微修改代码)。

          @Test fun stopInMiddleOfLambda() {
              var answer = "wrong"
              doStuff(fun() {
                  doStuff(fun() {
                      answer = "correct"
                      if (answer == "correct") {
                          return
                      }
                      answer = "wrong"
                  })
                  if(answer != "wrong") {
                      return
                  }
                  answer = "wrong"
              })
              assertEquals("correct", answer)
          }
      ...
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-11-14
        • 1970-01-01
        • 2014-09-11
        • 2017-03-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多