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)