-
if语句
val max = if (a > a1) a else a1
例子:
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
-
使用区间(in)
fun test() { val a = 99 if (a in 1..898) { Log.e("max", "a 在区间内 ") } }
结果:
max: a 在区间内
-
When 表达式(类似java的 switch 操作符)
fun test() { when (5) { 10 -> Log.e("when", "== 10") 20 -> Log.e("when", "== 20") //注意这个块 else -> { Log.e("when", " 不是 10 ,不是 20") } } }
else类似 java中switch 的 default
输出结果:when: 不是 10 ,不是 20
-
for语句
-
递增:关键词
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 => 24
2.递减:关键词
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
-
-
while语句(同Java中的while循环一样)
while(exp){ 其中exp为表达式 ... }
-
返回和跳转
在Kotlin中, 有三种跳转表达式的结构化:
return: 默认从直接包围它的函数或者匿名函数返回。
break: 终止直接包围它的循环。
continue: 继续下一次直接包围它的循环。
Kotlin之表达式
最新推荐文章于 2024-04-18 05:41:40 发布