如何在kotlin中的when语句中添加多个语句

我正在尝试为一个条件有多个报表。 例如:这是when语句的示例代码。

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

当x是1时,我也想要像x + = 10这样的额外语句,我该怎么做呢?

你有问题的解决方案与“注意块”评论。 分支的when可以是可以包含任意数量的语句的块:

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

编写单个语句分支只是简化了语法,所以不需要用{}来包围它。