If 表达式
1、在 Kotlin 中,if是一个表达式,即它会返回一个值。
// if 传统用法
var max = a
if (a < b) max = b
// if else 传统用法
var max: Int
if (a > b) {
max = a
} else {
max = b
}
// 作为表达式,如果作为表达必须要有else
val max = if (a > b) a else b
2、if 的分支可以是代码块,最后一行就是返回值
val max = if (a > b) {
print("Choose a")
a //返回值
} else {
print("Choose b")
b //返回值
}
When 表达式
1、when 表达式取代了类 Java 语言的 switch 语句
when (x) {
1 -> print("x == 1")
2 -> print("x == 2")
else -> { // 注意这个块
print("x is neither 1 nor 2")
}
}
2、分支需要用相同的方式处理,则可以把多个分支条件放在一起,用逗号分隔
when (x) {
0, 1 -> print("x == 0 or x == 1")
else -> print("otherwise")
}
3、用任意表达式(而不只是常量)作为分支条件
when (x) {
parseInt(s) -> print("s encodes x")
else -> print("s does not encode x")
}
4、检测一个值在(in)或者不在(!in)一个区间或者集合中
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")
}
5、检测一个值是(is)或者不是(!is)一个特定类型的值
fun hasPrefix(x: Any) = when(x) {
is String -> x.startsWith("prefix")
else -> false
}
6、不提供参数,所有的分支条件都是简单的布尔表达式,而当一个分支的条件为真时则执行该分支,可以用来取代 if-else if 链
when {
x.isOdd() -> print("x is odd")
y.isEven() -> print("y is even")
else -> print("x+y is odd.")
}
7、 when 的常规用法
when 主语中引入的变量的作用域仅限于 when 主体。
fun Request.getBody() =
when (val response = executeRequest()) {
is Success -> response.body
is HttpError -> throw HttpException(response.status)
}
For 循环
1、for 循环可以对任何提供迭代器(iterator)的对象进行遍历
只有一行处理
for (item in collection) print(item)
循环体可以是一个代码块
for (item: Int in ints) {
// ……
}
2、数字区间上迭代
for (i in 1..3) {
println(i) //i=1,2,3
}
for (i in 6 downTo 0 step 2) {
println(i) //i=6 ,4 ,2 ,0
}
4、通过索引遍历一个数组或者一个 list
for (i in array.indices) {
println(array[i])
}
5、用库函数 withIndex
for ((index, value) in array.withIndex()) {
println("the element at $index is $value")
}
While 循环
while 与 do…while 跟Java一样
while (x > 0) {
x--
}
do {
val y = retrieveData()
} while (y != null) // y 在此处可见