What I would like to do:
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
}
I cannot write break:
'break' and 'continue' are not allowed in 'when' statements. Consider using labels to continue/break from the outer loop.
Is it a way to return/break from when statements? Or what is the best way to solve it?
You can use labels to break/continue/return. e.g.:
transactions@ for (transaction in transactions) {
    when (transaction.state) {
        Transaction.Type.EXPIRED,
        Transaction.Type.BLOCKED -> {
            break@transactions
        }
    }
}
See Returns and Jumps - Kotlin Programming Language for more details.
Work around using 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
    }
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With