Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

break or return from when expressions

Tags:

kotlin

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?

like image 206
Feeco Avatar asked Jan 31 '17 18:01

Feeco


2 Answers

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.

like image 102
mfulton26 Avatar answered Nov 12 '22 08:11

mfulton26


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
    }
}
like image 4
Vyacheslav Lukianov Avatar answered Nov 12 '22 09:11

Vyacheslav Lukianov