我想做什么:
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
陈述的方式吗?或者解决它的最佳方法是什么?
答案 0 :(得分:13)
您可以将run
与return 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
}
}
}
答案 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
}
}