Kotlin簡化了 條件判斷,還簡化了 循環判斷
除了文字版本,也有Xmind版本 github地址
本文需要幾個問題
① for循環支持幾種模式?
② for循環如何取值?去index索引
③ label怎麼用?簡化了什麼?又需要注意什麼?
④ break continue集合label,可以怎麼跳?
本節有5個部分
- For循環
- while與do…while循環
- 返回和跳轉
- break和continue
- 標籤
for循環
支持幾種類型
- iterator迭代器(java也有)
for (item: Int in ints) {
// ……
}
- 索引遍歷。類似for(int i = 0; i < sum; i ++)。這又是簡化
for (i in array.indices) {
print(array[i])
}
- 庫函數withIndex。對簡化for(int i = 0; i < sum; i ++)做了升級。直接取出了值
for ((index, value) in array.withIndex()) {
println("the element at $index is $value")
}
"在區間上遍歷"會編譯成優化的實現而不會創建額外對象
任何提供了迭代器的對象 都可以被循環遍歷
循環遍歷的條件
有一個成員函數或者擴展 iterator()函數
- 有一個成員函數或者擴展函數 next(),並且
- 有一個成員函數或者擴展函數 hasNext() 返回 Boolean。
while 與 do…while 循環
與java一樣,這裏就不詳述
返回和跳轉
與java一樣,這裏就不詳述
break和continue
- 任何表達式都可以用標籤(label)來標記
- 標籤的格式爲標識符後跟 @ 符號,例如:abc@、fooBar@
loop@ for (i in 1..100) {
for (j in 1..100) {
if (……) break@loop
}
}
解析一下。
在表達式前,➕標籤;
- break:跳轉的位置(到剛好位於該標籤指定的循環後面的執行點)
- continue:繼續標籤指定的循環的下一次迭代
標籤處返回
標籤限制的 return 允許我們從外層函數返回
範例一
fun foo() {
ints.forEach {
if (it == 0) return
print(it)
}
}
return是從 包圍它的 函數foo()返回
範例二
fun foo() {
ints.forEach lit@ {
if (it == 0) return@lit
print(it)
}
}
這裏從forEach中返回。
範例三
自帶隱式標籤;與接受該lambda的函數同名
fun foo() {
ints.forEach {
if (it == 0) return@forEach
print(it)
}
}
範例四
返回值: 1
fun foo() {
abc@ ints.forEach(fun(value: Int) {
if (value == 0) return@abc 1
print(value)
})
}
從標籤@abc返回1