gpt4 book ai didi

kotlin - break or return from when 表达式

转载 作者:IT老高 更新时间:2023-10-28 13:33:38 25 4
gpt4 key购买 nike

我想做的事:

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:

'break' and 'continue' are not allowed in 'when' statements. Consider using labels to continue/break from the outer loop.

这是一种从 when 语句中 return/break 的方法吗?或者最好的解决方法是什么?

最佳答案

您可以使用 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
}

关于kotlin - break or return from when 表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41964644/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com