例子:
fun test() { var a: Int = 3 var a1: Int = 4 val max = if (a > a1) a else a1 Log.e("max", "max " + max) }输出结果:
max: max 4结果:
max: a 在区间内else类似 java中switch 的 default 输出结果:
when: 不是 10 ,不是 20递增:关键词 until
fun test() { // 从10开始,循环15次,且步长为1的递增 for (i in 10 until 25) { Log.e("when", "i => $i \t") } }输出结果:
when: i => 10 when: i => 11 when: i => 12 when: i => 13 when: i => 14 when: i => 15 when: i => 16 when: i => 17 when: i => 18 when: i => 19 when: i => 20 when: i => 21 when: i => 22 when: i => 23 when: i => 242.递减:关键词 downTo
fun test() { // 从25开始,循环16次,且步长为1的递减 for (i in 25 downTo 10) { Log.e("when", "i => $i \t") } }输出结果:
when: i => 25 when: i => 24 when: i => 23 when: i => 22 when: i => 21 when: i => 20 when: i => 19 when: i => 18 when: i => 17 when: i => 16 when: i => 15 when: i => 14 when: i => 13 when: i => 12 when: i => 11 when: i => 10 .. 循环 fun test() { // 从15开始,循环10次,且步长为1的递减 for (i in 15..25) { Log.e("when", "i => $i \t") } }输出结果:
when: i => 16 when: i => 17 when: i => 18 when: i => 19 when: i => 20 when: i => 21 when: i => 22 when: i => 23 when: i => 24 设置步长 step fun test() { for (i in 15..25 step 4) { Log.e("when", "i => $i \t") } }输出结果:
when: i => 15 when: i => 19 when: i => 23 indices属性遍历数组 fun test() { var arrayLists = arrayOf("15", "68", "79", "09", "6") for (i in arrayLists.indices) { Log.e("arrayLists", "arrayLists[$i] => " + arrayLists[i]) } }输出结果:
arrayLists[0] => 15 arrayLists[1] => 68 arrayLists[2] => 79 arrayLists[3] => 09 arrayLists[4] => 6 withIndex()方法遍历 fun test() { var arrayLists = arrayOf("15", "68", "79", "09", "6") for ((index,value) in arrayLists.withIndex()) { Log.e("arrayLists", "index => $index \t value => $value") } }输出结果:
index => 0 value => 15 index => 1 value => 68 index => 2 value => 79 index => 3 value => 09 index => 4 value => 6在Kotlin中, 有三种跳转表达式的结构化: return: 默认从直接包围它的函数或者匿名函数返回。 break: 终止直接包围它的循环。 continue: 继续下一次直接包围它的循环。
