添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams //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?

I think I agree that break functionality would be nice (though you could always do the if/else thing). Just suggesting a workaround until such time as the Kotlin team decided to implement (or not). Oliver Dain Jan 31, 2017 at 19:03 //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 that's odd @IgorGanapolsky, you may need ask a question on SO if you still have the issue when trying to create a minimal, reproducible example it should work, here is a Kotlin Playground link to demonstrate run + return@run : pl.kotl.in/yBP4E8ycc mfulton26 Sep 25, 2020 at 18:46

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.

Good workaround, but I cannot accept it as the answer because it may be some code after when. – Boris Jan 31, 2017 at 20:24 @Feeco. Thank you. I think I slightly misunderstood your question. I'll post another answer. – mfulton26 Jan 31, 2017 at 20:36 //about 10 more types Transaction.Type.BLOCKED -> { if (type == Transaction.Type.BLOCKED && closeAnyway) { close(this) return@apply //common logic //other types

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.