从表达式中断或返回

Fee*_*eco 15 kotlin

我想做什么:

when(transaction.state) {
    Transaction.Type.EXPIRED,
    //about 10 more types
    Transaction.Type.BLOCKED -> {
        if (transaction.type == Transaction.Type.BLOCKED && transaction.closeAnyway) {
            close(transaction)
            break //close if type is blocked and has 'closeAnyway' flag
        }
        //common logic
    }
    //other types
}
Run Code Online (Sandbox Code Playgroud)

我不能写break:

'when'语句中不允许'break'和'continue'.考虑使用标签从外循环继续/中断.

这是一种return/break来自when陈述的方式吗?或者解决它的最佳方法是什么?

mfu*_*n26 20

你可以用run在标签的回报:

when(transaction.state) {
    Transaction.Type.EXPIRED,
    //about 10 more types
    Transaction.Type.BLOCKED -> run {
        if (transaction.type == Transaction.Type.BLOCKED && transaction.closeAnyway) {
            close(transaction)
            return@run //close if type is blocked and has 'closeAnyway' flag
        }
        //common logic
    }
    //other types
}
Run Code Online (Sandbox Code Playgroud)


mfu*_*n26 8

您可以使用标签来中断/继续/返回。例如:

transactions@ for (transaction in transactions) {
    when (transaction.state) {
        Transaction.Type.EXPIRED,
        Transaction.Type.BLOCKED -> {
            break@transactions
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

有关更多详细信息,请参见返回和跳转-Kotlin编程语言

  • 很好的解决方法,但我不能接受它作为答案,因为它可能是“when”之后的一些代码。 (2认同)