Boaris
Boaris

Reputation: 5226

break or return from when expressions

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?

Upvotes: 35

Views: 25636

Answers (3)

mfulton26
mfulton26

Reputation: 31234

You can use run with a 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
}

Upvotes: 48

Vyacheslav Lukianov
Vyacheslav Lukianov

Reputation: 2053

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
    }
}

Upvotes: 4

mfulton26
mfulton26

Reputation: 31234

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.

Upvotes: 16

Related Questions