if表達(dá)式
// Traditional usage
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做表達(dá)式而不是表示一種狀態(tài)邏輯,則必須有else的分支。
When表達(dá)式
when代替switch結(jié)構(gòu)
when (x) {
1 -> print("x == 1")
2 -> print("x == 2")
else -> { // Note the block
print("x is neither 1 nor 2") }
}
when接口會順序匹配他的所有條件分支,并執(zhí)行所有滿足條件的分支。when不但能用于表達(dá)式,同時也能表示狀態(tài)值。如果當(dāng)作時表達(dá)式,滿足條件的分支將是整個表達(dá)式的值。如果作為狀態(tài)值,則條件所對應(yīng)的值不會影響表達(dá)式的值,只是滿足條件的最后一個分支的值為整個表達(dá)式的值。
如果有多個條件需要滿足,則只需把多個條件連接寫出來用逗號隔開:
when (x) {
0, 1 -> print("x == 0 or x == 1") else -> print("otherwise")
}
我們可以用任意的表達(dá)式作為條件而不僅僅是常數(shù):
when (x) {
parseInt(s) -> print("s encodes x") else -> print("s does not encode x")
}
我們也可以去檢驗(yàn)一個值是否存在一個范圍內(nèi)或者集合中通過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")
}
另外也可用于判斷一些特殊類型:
val hasPrefix = when(x) {
is String -> x.startsWith("prefix") else -> false
}
when也可以替換if-else if結(jié)構(gòu)題,當(dāng)不寫參數(shù)的時候,每個條件分支為boolean表達(dá)式,分支為true的時候執(zhí)行:
when {
x.isOdd() -> print("x is odd") x.isEven() -> print("x is even") else -> print("x is funny")
}
for循環(huán)
for循環(huán)可以迭代任何可以迭代的東西。語法如下:
for (item in collection) print(item)
也可以寫為代碼塊:
for (item: Int in ints) {
// ...
}
如前所述,迭代器提供了三個方法:
-
iterator()生成迭代器 -
next()游標(biāo) -
hasNext()boolean
如下對array進(jìn)行遍歷:
for (i in array.indices) {
print(array[i])
}
for ((index, value) in array.withIndex()) {
println("the element at $index is $value")
}
While循環(huán)
while (x > 0) {
x--
}
do {
val y = retrieveData()
} while (y != null) // y is visible here!
Break和contunue在循環(huán)中的使用
kotlin支持循環(huán)體中傳統(tǒng)的break和continue操作符
返回和跳過
kotlin又三種跳轉(zhuǎn)結(jié)構(gòu)表達(dá)式:
- return。默認(rèn)跳出最近的方法體。
- break。跳出最近的循環(huán)
- continue。跳過當(dāng)前步驟,繼續(xù)下一步循環(huán)
以上操作符可以運(yùn)用在比較大的表達(dá)式中
val s = person.name ?: return
break和continue標(biāo)簽
任何表達(dá)式在kotlin中建議使用label。lable接口為lableName@.例如abc@,foobar.標(biāo)記一個表達(dá)式,我們直接將標(biāo)記放在表達(dá)式之前:
loop@ for (i in 1..100) { // ...
}
我們可以使用break或者continue結(jié)束某個帶標(biāo)簽的表達(dá)式
loop@ for (i in 1..100) {
for (j in 1..100) {
if (...) break@loop
}
}
return某個標(biāo)簽表達(dá)式
fun foo() {
ints.forEach {
if (it == 0) return
print(it)
}
}
可以通過增加標(biāo)簽,而結(jié)束對應(yīng)方法
fun foo() {
ints.forEach lit@ {
if (it == 0) return@lit
print(it)
}
}
在lambda表達(dá)式重,通常會引用內(nèi)部方法名為label
fun foo() {
ints.forEach {
if (it == 0) return@forEach
print(it)
}
}
當(dāng)然,也可以獎lambda表達(dá)式替換為匿名方法
fun foo() {
ints.forEach(fun(value: Int) {
if (value == 0) return
print(value)
})
}
當(dāng)返回一個值時,會返回對應(yīng)對象的引用值
return@a 1
返回的不是一個表達(dá)式,而是 標(biāo)簽為1的值為1.