if , when , for , while
if 表達(dá)式
在 Kotlin 中,if 是帶有返回值的表達(dá)式。因此Kotlin沒有三元運(yùn)算符(condition ? then : else),因?yàn)?if 語句可以做到同樣的事。
// 傳統(tǒng)用法
var max = a
if (a < b) max = b
// 帶 else
var max: Int
if (a > b) {
max = a
}
else{
max = b
}
// 作為表達(dá)式
val max = if (a > b) a else b
When 表達(dá)式
when 取代了 C 風(fēng)格語言的 switch 。最簡單的用法像下面這樣
when (x) {
1 -> print("x == 1")
2 -> print("x == 2")
else -> { // Note the block
print("x is neither 1 nor 2")
}
}
注:如果把 when 做為表達(dá)式的話 else 分支是強(qiáng)制的
如果有分支可以用同樣的方式處理的話,分支條件可以連在一起
when (x) {
0,1 -> print("x == 0 or x == 1")
else -> print("otherwise")
}
可以用任意表達(dá)式作為分支的條件
when (x) {
parseInt(s) -> print("s encode x")
else -> print("s does not encode x")
}
is in
in 或者 !in 檢查值是否值在一個(gè)范圍或一個(gè)集合中
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 來判斷值是否是某個(gè)類型。
val hasPrefix = when (x) {
is String -> x.startsWith("prefix")
else -> false
}
for 循環(huán)
for 循環(huán)可以對所有提供迭代器的變量進(jìn)行迭代。等同于 C# 等語言中的 foreach。語法形式
for (item in 1..10)
println(item)
for (i in array.indices)
print(array[i])
while 循環(huán)
while 和 do...while 和其它語言沒什么區(qū)別
while (x > 0) {
x--
}
do {
val y = retrieveData()
} while (y != null) // y 在這是可見的