从表达式中断或返回

时间:2017-01-31 18:13:46

标签: 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
}

我不能写break

  'when'语句中不允许

'break'和'continue'。考虑使用标签继续/从外循环中断。

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

3 个答案:

答案 0 :(得分:13)

您可以将runreturn at label

一起使用
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
}

答案 1 :(得分:4)

您可以使用标签来中断/继续/返回。 e.g:

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

有关详细信息,请参阅Returns and Jumps - Kotlin Programming Language

答案 2 :(得分:1)

使用apply()

进行解决
transaction.apply {
    when(state) {
        Transaction.Type.EXPIRED,
        //about 10 more types
        Transaction.Type.BLOCKED -> {
            if (type == Transaction.Type.BLOCKED && closeAnyway) {
                close(this)
                return@apply
            }
            //common logic
        }
        //other types
    }
}