Kotlin二进制if条件

smtd7mpg  于 2023-11-21  发布在  Kotlin
关注(0)|答案(1)|浏览(330)

我对这个节目很困惑。

  1. fun main(args: Array<String>) {
  2. val condition1 = true
  3. val condition2 = false
  4. val condition3 = true
  5. val state = (if (condition1) 1 else 0) shl 2 or
  6. (if (condition2) 1 else 0) shl 1 or
  7. (if (condition3) 1 else 0)
  8. println(state)
  9. when (state) {
  10. 0b100 -> println("Only condition1 is true.")
  11. 0b010 -> println("Only condition2 is true.")
  12. 0b001 -> println("Only condition3 is true.")
  13. 0b101 -> println("condition1 and condition3 are true.")
  14. 0b110 -> println("condition1 and condition2 are true.")
  15. 0b011 -> println("condition2 and condition3 are true.")
  16. 0b111 -> println("All conditions are true.")
  17. else -> println("All conditions are false.")
  18. }
  19. }

字符串
我期望打印“condition1 and condition3 are true.”.但这段代码总是返回else块“All conditions are false.”
此外,我的IDE警告'永远无法访问'如下。


的数据
为什么会这样?有人能帮帮我吗?

4urapxun

4urapxun1#

你忘记了一些括号,你的表达式的第一行的结果是用(if (condition2) 1 else 0)得到或艾德,然后整个结果左移了1,所以现在第一个1已经左移了3。
在第二行添加括号以修复它:

  1. val state = (if (condition1) 1 else 0) shl 2 or
  2. ((if (condition2) 1 else 0) shl 1) or
  3. (if (condition3) 1 else 0)

字符串
实际上,只有一个分支是可到达的,因为你只使用局部常量输入和局部计算。编译器只警告你它足够复杂可以检测到的那些分支。

相关问题