从表达式中断或返回
我想做什么:
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
断言? 或者什么是解决它的最好方法?
你可以用标签返回来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 }
您可以使用标签打破/继续/返回。 例如:
transactions@ for (transaction in transactions) { when (transaction.state) { Transaction.Type.EXPIRED, Transaction.Type.BLOCKED -> { break@transactions } } }
请参阅返回和跳转 – Kotlin编程语言的更多详细信息。
解决使用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 } }