If Expression

在Kotlin中,if是一个表达式,它有返回类型。因此Kotlin中不再需要三元表达式。

1
var max = if (a > b) a else b

if分支也可以是代码块(blocks),代码块的末尾是返回值。

1
2
3
4
5
6
7
var max = if (a > b) {
print("Choose a")
a // a会被赋值给max
} else {
print("Choose b")
b // b会被赋值给max
}

When Expression

when替代了switch语句,简单的例子像这样:

1
2
3
4
5
6
7
when (x) {
1 -> print("x == 1")
2 -> print("x == 2")
else -> {
print("x is neither 1 or 2")
}
}

如果多个分支使用同样的处理逻辑,那么可以用逗号将它们结合起来:

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

分支中除了使用常量(上例中的1、2),也可以使用函数(arbitrary expressions):

1
2
3
4
when (x) {
parseInt(s) -> print("s encodes x")
esle -> print("s does not encode x")
}

也可以用in!in判断一个值是否在一个范围(range)或集合(collection)中:

1
2
3
4
5
6
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!is来检查一个值是否是某个类型:

1
2
3
4
val hasPrefix = when(x) {
is String -> x.startsWith("prefix") // 注意这里s已经被自动转为String类型了
else -> false
}

when还可以用来取代if-else if。如果没有传参数,那么分支条件就是简单的boolean表达式,当条件为true时分支就会被执行:

1
2
3
4
5
when {
x.isOdd() -> print("x is odd")
x.isEven() -> print("x is even")
else -> print("x is funny")
}

For Loops

感觉没什么特别的,跟Java一样:

1
2
3
4
5
for (item in collection)
print(item)

for (i in array.indices)
print(array[i])

While Loops

也没什么特别的:

1
2
3
4
5
6
7
while (x > 0) {
x--
}

do {
val y = retrieveData()
} while (y != null) // 注意虽然y是在大括号内部定义的,但这里仍然可以访问到