Kotlin基础教程-流程控制语句

Control Flow

If表达式

Kotlin中,if是一个表达式,有返回值。但不支持三目运算

val a = 1
    val b = 2
    var max = a
    if (a < b) max = b
    var max1: Int
    if (a > b) {
        max1 = a
    } else {
        max1 = b
    }

    val max3 = if (a > b) a else b

如果if分支是代码块,那么代码块的最后一个表达式默认为返回值

 val max4 = if (a > b) {
        print("Choose a")
        a
    } else {
        print("Choose b")
        b
    }

如果if表达式返回结果或者将if表达式作为变量赋值的话,都不能缺少else语句块。

when表达式

替代Java中的switch语句

when (x) {
    1 -> print("x == 1")
    2 -> print("x == 2")
    else -> { // Note the block
        print("x is neither 1 nor 2")
    }
}

when语句块也可以作为表达式或者声明语句,如果是表达式,符合条件的分支会作为整个表达式的结果返回。如果作为声明式语句,个别语句会被忽略。

else分支在所有条件都不满足的情况下,会走该分支。如果作为表达式,else分支是必须要有的。

如果很多个分支,返回的结果一样,那么可以合并分支,用,号分割:

when (x) {
    0, 1 -> print("x == 0 or x == 1")
    else -> print("otherwise")
}

也可以使用任意表达式作为判断条件:

when (x) {
    parseInt(s) -> print("s encodes x")
    else -> print("s does not encode x")
}

也可以使用范围range作为判断条件,判断传入的值是否处于某个range中。

when (x) {
    in 1..10 -> print("x is in the range")
    in validNumbers -> print("x is valid")
    !in 10..20 -> print("x is outside the range")
    else -> print("none of the above")
}

当然is语句也是支持的

fun hasPrefix(x: Any) = when(x) {
    is String -> x.startsWith("prefix")
    else -> false
}

如果不传入参数,这分支判断条件是某个条件为true,才走该分支。

For循环

for循环可以遍历任何迭代器对象

  • 含有iterator()函数,别返回迭代元素类型
    • 含有next()函数
    • 含有hasNext()函数,返回布尔值

上面三个方法称为操作器。
但是如果在Array对象进行for循环的时候,不创建迭代器,而是基于索引值进行遍历。

如果想遍历的时候取出索引值,你可以使用indices处理数组:

val array = arrayOf(2,34,53,435,32)
for(index in array.indices){
        println(index)
    }

这里写图片描述

withIndex 同时获取索引和值

for ((index, value) in array.withIndex()) {
        println("the element at $index is $value")
    }

while循环

while语句有2种格式

while

while (x > 0) {
    x--
}

do while

do {
    val y = retrieveData()
} while (y != null) 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值