在Kotlin中,if表達式會返回一個值。因此沒有三元運算符(condition ? then : else),因為結構比較簡單,if表達式工作沒有什么問題。
// 傳統(tǒng)用法
var max = a
if (a < b) max = b
// With else
var max: Int
if (a > b) {
max = a
} else {
max = b
}
// As expression
val max = if (a > b) a else b
if分支可以是塊,并且最后一個表達式是塊的值:
val max = if (a > b) {
print("Choose a")
a
} else {
print("Choose b")
b
}
如果使用if作為表達式而不是語句(例如,返回其值或將其分配給變量),則表達式需要具有其他分支。
當替換類似C語言的交換運算符時。 最簡單的形式就是這樣 -
when (x) {
1 -> print("x == 1")
2 -> print("x == 2")
else -> { // Note the block
print("x is neither 1 nor 2")
}
}
當它的參數(shù)與所有when語句中的分支按順序進行匹配,直到滿足一些分支條件。when可以用作表達式或作為語句。 如果將其用作表達式,則滿足分支的值將變?yōu)檎w表達式的值。
如果將when用作語句,則忽略各個分支的值。 (就像if語句,每個分支可以是一個塊,其值是塊中最后一個表達式的值。)
如果其他的(if/else if)分支條件不滿足,則評估求值else分支。如果when用作表達式,則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")
}
還可以檢查值是否在或不在(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")
}
另一個可能性是檢查一個值是否(is/!is)為指定類型的值。請注意,由于智能轉換,可以訪問類型的方法和屬性,而無需任何額外的檢查。
fun hasPrefix(x: Any) = when(x) {
is String -> x.startsWith("prefix")
else -> false
}
when也可以用來替代if-else if語句語法。 如果沒有提供參數(shù),則分支條件是簡單的布爾表達式,當條件為真時執(zhí)行分支:
when {
x.isOdd() -> print("x is odd")
x.isEven() -> print("x is even")
else -> print("x is funny")
}
for循環(huán)提供迭代器用來遍歷任何東西。 語法如下:
for (item in collection) print(item)
主體可以是一個塊,如下 -
for (item: Int in ints) {
// ...
}
如前所述,for迭代提供迭代器的任何內容,即
iterator(),它的返回類型:next()和hasNext()。所有這三個函數(shù)都需要被標記為運算符。
for循環(huán)數(shù)組被編譯為一個基于索引的循環(huán),它不會創(chuàng)建一個迭代器對象。如果要遍歷具有索引的數(shù)組或列表,可以這樣做:
for (i in array.indices) {
print(array[i])
}
請注意,這個“通過范圍的迭代”被編譯成最佳實現(xiàn),沒有創(chuàng)建額外的對象。
或者,可以使用withIndex庫函數(shù):
for ((index, value) in array.withIndex()) {
println("the element at $index is $value")
}
while 和 do..while 用法和java語言中一樣,如下 -
while (x > 0) {
x--
}
do {
val y = retrieveData()
} while (y != null) // y is visible here!
Kotlin在循環(huán)中,支持傳統(tǒng)的break和continue運算符。請參考返回和跳轉。