在 Kotlin 中选择“when”与“if/else”的标准是什么?

Roo*_*nil 7 java if-statement switch-statement kotlin

我正在从 Java 转移到 Kotlin,并了解 Java switch 和 Kotlin when 语句之间的各种差异。

我的问题是,当您在一系列“if”和“else if”块中选择“when”时,这些差异是否会改变标准?

例如,在 Java 中,当有 5 种或更多情况时,“switch”通常比“else-ifs”更有效,否则大致可比。当语句是布尔值时,通常首选 if-else。这在 Kotlin 中是否类似?我在编写代码时是否应该考虑与 Java 不同的其他原因 - 即可读性标准等。

我希望得到有关该主题的更深入阅读的答案或链接 - 我一直在努力寻找任何可以进行良好成本效益分析的来源。

use*_*900 7

Kotlin benefits over java is concise syntax

when has a better design. It is more concise and powerful than a traditional switch

Also more readable related to if else:

when is that it can be used without an argument. In such case it acts as a nicer if-else chain: the conditions are Boolean expressions. As always, the first branch that matches is chosen. Given that these are boolean expression, it means that the first condition that results True is chosen.

when {
    number > 5 -> print("number is higher than five")
    text == "hello" -> print("number is low, but you can say hello")
}
Run Code Online (Sandbox Code Playgroud)

The advantage is that a when expression is cleaner and easier to understand than a chain of if-else statements.


pap*_*ika 6

来自Kotlin 编码约定
优先使用 if 来表示二进制条件而不是 when。如果有三个或更多选项,最好使用 when 。