Kotlin中如何将if/else if语句改写为when语句?
把Kotlin的if/else if改成when语句的正确方式
首先得说,你贴的代码逻辑有问题——所有if条件都是常量之间的比较(比如32 < 47),这些条件永远是true或false,导致分支根本不会按你预期的触发(比如第一个32<47永远为true,只会打印"47",后面的else if全白写了,最后那个单独的41<60也永远为true,会打印"Normal")。
你应该是想基于某个温度变量来判断天气,先把逻辑修正,再改成when语句。
第一步:修正原逻辑(基于温度变量)
假设你有个温度变量temperature,正确的if/else if逻辑应该是这样的:
fun main() { val temperature = 25 // 替换成你实际的温度值 if (temperature < 20) { println("Very Cold weather") } else if (temperature < 40) { println("Cold") } else if (temperature < 47) { println("47") } else if (temperature < 60) { println("Normal") } }
第二步:改写成when语句
Kotlin的when语法更简洁,不用写一堆else if,直接按顺序写条件分支:
fun main() { val temperature = 25 // 替换成你实际的温度变量 when { temperature < 20 -> println("Very Cold weather") temperature < 40 -> println("Cold") temperature < 47 -> println("47") temperature < 60 -> println("Normal") else -> println("Other weather") // 可选:所有条件都不满足时的默认处理 } }
关键注意点
- 分支顺序很重要:when是从上到下匹配的,先满足的分支会先执行,然后直接跳出when。比如如果把
temperature <60放在最前面,那后面的temperature <47永远不会触发。 - 条件写法灵活:除了
<,还可以用in来写范围,比如temperature in 20..39等价于temperature >=20 && temperature <=39,代码可读性更高:when { temperature < 20 -> println("Very Cold weather") temperature in 20..39 -> println("Cold") temperature in 40..46 -> println("47") temperature in 47..59 -> println("Normal") else -> println("Other weather") }
内容的提问来源于stack exchange,提问作者Lynn
相关产品推荐
相关产品推荐

