我试图为一个条件有多个语句.例如:这是when语句的示例代码.
when (x) {
1 -> print("x == 1")
2 -> print("x == 2")
else -> { // Note the block
print("x is neither 1 nor 2")
}
}
Run Code Online (Sandbox Code Playgroud)
当x为1时,我还想要一个额外的声明,比如x + = 10,我该怎么办呢?
zsm*_*b13 17
您可以通过"注意块"注释在您的问题中找到解决方案.分支when可以是可以包含任意数量语句的块:
when(x) {
1 -> {
println("x == 1")
x += 10
println("x == 11")
}
2 -> { ... }
else -> { ... }
}
Run Code Online (Sandbox Code Playgroud)
编写单个语句分支只是具有简化的语法,因此您不需要将其包围{}.
| 归档时间: |
|
| 查看次数: |
4026 次 |
| 最近记录: |