Kotlin if else & when/else

tv_answer.text = if (is_odd == true) {
 "字符串1"
 } else {
 "字符串2"
 }

以上方便理解更简洁方式是

tv_answer.text = if (is_odd==true)  "字符串1" else  "字符串2"

when/else

var count:Int = 0
btn_when_simple.setOnClickListener {
when (count) {
0 -> tv_answer.text = "字符串1"
1 -> tv_answer.text = "字符串2"
//if语句可以没有eles,但是when语句必须有else
else -> tv_answer.text = "字符串3"
}
count = (count+1) % 3
}

有一个区间范围感觉比较用的多

tv_answer.text = when (count) {
  1,3,5,7,9 -> "字符串1"
  in 13..19 ->"字符串2"
  //非6-10
  !in 6..10  ->"字符串3"
  //else别忘了
  else -> "xxx"
  }
count = (count+1) % 20
}



你可能感兴趣的:(Kotlin if else & when/else)