How to add multiple statements inside a when statement in kotlin

12,205

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

Share:
12,205

Related videos on Youtube

Nicholas Chow
Author by

Nicholas Chow

Updated on September 14, 2022

Comments

  • Nicholas Chow
    Nicholas Chow over 1 year

    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?

  • marstran
    marstran almost 7 years
    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?
  • zsmb13
    zsmb13 almost 7 years
    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.
  • voddan
    voddan almost 7 years
    The nicest way IMO is -> ({}). And I totally agree it is weird
  • zsmb13
    zsmb13 almost 7 years
    Ah, that is pretty neat, actually.