在Kotlin 中 if是個表達式 ,它會返回一個值,能夠替換三元運算符(?:)html
//表達式
val a = if (b > c) b else c
val a = if (b > c) {
a
}else {
b
}
複製代碼
when 相似 其餘語言的switch. when 將它的參數與全部的分支條件順序比較,直到某個分支知足條件bash
when 也能夠用來取代 if-else if鏈框架
// 表達式 塊
when(a) {
0 -> {
//
}
1 -> {
//
}
else -> {
//
}
}
// 簡單表達式
when(a) {
0 -> print(0)
1 -> print(1)
else -> {
print("else")
}
}
// 並 表達式
when(a) {
0,1 -> print("0 || 1")
else -> print("else")
}
// 表達式 函數表達式
fun show(a: Int) : Int {
return a * a
}
when (a) {
show(a) -> print("a")
else -> print("else")
}
// 區間 in
when(x) {
in 1..3 -> print("1..3")
!in 4..5 -> print("not in 4 - 5")
else -> print("else")
}
// is
when(x) {
is String -> print("x is String")
is Int -> print(x is String)
else -> print("else")
}
複製代碼
for 循環能夠對任何提供迭代器(iterator)的對象進行遍歷函數
集合框架包括Iterable、Iterator 和 Collectionui
- size()、isEmpty()、contains()、constainsAll():集合屬性和元素查詢是都有的;
- iterator():都有迭代器;
- add()、addAll():添加元素,可變集合才能添加;
- remove()、removeAll():刪除元素,可變集合才能刪除;
- retainAll()、clear():一樣涉及到對元素的刪除,可變集合纔有的功能。
// 表達式
for(i in 1..3) {
println(i)
}
for(i in 9 step 2) {
print(i)
}
// indices 函數
for (i in array.indices) {
println(array[i])
}
//withIndex 函數
for ((index, value) in array.withIndex()) {
println("the element at $index is $value")
}
複製代碼
while(x > 0) {
x--
}
do {
//
}whle(x > 0)
複製代碼
return。默認從最直接包圍它的函數或者匿名函數返回。spa
break。終止最直接包圍它的循環。.net
continue。繼續下一次最直接包圍它的循環。code
for(i in 0..10) {
if i == 2 {
break
//return
//continue
}
}
複製代碼
在 Kotlin 中任何表達式均可以用標籤來標記,標籤的格式爲標識符後跟
@
符號htm
aaa@ for (i in 0..20) {
for (j in 0...300) {
if j = 100 {
break@aaa
}
}
}
複製代碼