Kotlin位运算条件判断异常及IDE不可达警告问题排查
问题原因:运算符优先级错误导致位计算结果不符合预期
核心问题是Kotlin中位移运算符(shl)的优先级高于按位或运算符(or),导致代码的实际计算顺序和预期完全不同:
- 你预期的计算逻辑:每个条件对应的0/1先单独左移对应位数,再按位或合并,最终得到
0b101(十进制5):(1 shl 2) or (0 shl 1) or 1 = 4 or 0 or 1 = 5 - 实际计算顺序:由于
shl优先级更高,代码会先计算(1 shl 2) or 0得到4,再将这个结果左移1位得到8,最后和1按位或得到0b1001(十进制9)。这个值不在你when分支的匹配列表中,因此会进入else分支;同时IDE会因为分支未覆盖该值,标记部分分支为不可达。
修复方案
给每个位移操作的结果单独加括号,强制指定计算顺序:
fun main(args: Array<String>) { val condition1 = true val condition2 = false val condition3 = true val state = ((if (condition1) 1 else 0) shl 2) or ((if (condition2) 1 else 0) shl 1) or (if (condition3) 1 else 0) println(state) when (state) { 0b100 -> println("Only condition1 is true.") 0b010 -> println("Only condition2 is true.") 0b001 -> println("Only condition3 is true.") 0b101 -> println("condition1 and condition3 are true.") 0b110 -> println("condition1 and condition2 are true.") 0b011 -> println("condition2 and condition3 are true.") 0b111 -> println("All conditions are true.") else -> println("All conditions are false.") } }
或者拆分变量,让逻辑更清晰:
fun main(args: Array<String>) { val condition1 = true val condition2 = false val condition3 = true val bitCondition1 = if (condition1) 1 shl 2 else 0 val bitCondition2 = if (condition2) 1 shl 1 else 0 val bitCondition3 = if (condition3) 1 else 0 val state = bitCondition1 or bitCondition2 or bitCondition3 println(state) when (state) { 0b100 -> println("Only condition1 is true.") 0b010 -> println("Only condition2 is true.") 0b001 -> println("Only condition3 is true.") 0b101 -> println("condition1 and condition3 are true.") 0b110 -> println("condition1 and condition2 are true.") 0b011 -> println("condition2 and condition3 are true.") 0b111 -> println("All conditions are true.") else -> println("All conditions are false.") } }
内容的提问来源于stack exchange,提问作者sho
相关产品推荐
相关产品推荐

