27

I am trying to have multiple statements for one condition. For example: this is a sample code for when statement.

when (x) {
    1 -> print("x == 1")
    2 -> print("x == 2")
     else -> { // Note the block
        print("x is neither 1 nor 2")
   }
}

When x is 1, I also want to have an extra statement like x += 10, how can I do it?

1 Answer 1

45

You have the solution in your question with the "Note the block" comment. Branches of when can be blocks that can contain any number of statements:

when(x) {
    1 -> {
        println("x == 1")
        x += 10
        println("x == 11")
    }
    2 -> { ... }
    else -> { ... }
}

Writing a single statement branch just has a simplified syntax so that you don't need to surround it with {}.

Sign up to request clarification or add additional context in comments.

4 Comments

That's a bit weird. Everywhere else in the language, adding braces means it's a lambda. How would you make a when-expression that returns a lambda of type () -> Unit?
Hmm, that's a rather interesting question. You can do -> { { println("hello") } }, for example. The lambda is the last statement in the branch, and will be returned. You could also do -> fun() { println("hello") }, that might be more legible.
The nicest way IMO is -> ({}). And I totally agree it is weird
Ah, that is pretty neat, actually.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.