IF表達式
if在kotlin可以當做表達式使用跟java的三元操作符類似:
var max = if( a > b ) a else b
if分支可以使用代碼塊,最後一個表達式是返回值:
var max = if (a > b){
print(a)
a
}else{
print(b)
b
}
When表達式
kotlin使用when來替換switch語句,基本特性都跟switch差不多會對列出來的分支進行匹配滿足條件的分支會被執行。when可以當做表達式或者語句
如果使用when當前表達式滿足條件的分支會當做when的返回值。當when當做語句使用的時候會忽略所有分支的值。when的每個分支也可以是語句塊最後一個表達式是這個語句塊的值。
用做表達式:
var matchValue = 2
var result = when(matchValue){
1 -> 1
2 -> 2
else ->3
}
println(result)
用於語句:
matchValue = 3
when(matchValue) {
1 -> println(1)
2 -> println(2)
else -> println(3)
}
匹配多少值:
when(matchValue){
1,2,3 -> println(matchValue)
}
使用is
與!is
:
var isInt = when(matchValue){
is Int -> println(matchValue)
else -> false
}
使用in
與!in
:
var valueIn = when(matchValue){
in 1..3 -> true
else -> false
}
當when沒有提供一個值時它的分支是boolean表達式when會執行爲真的分支:
var valueIn = when(matchValue){
in 1..3 -> true
else -> false
}
for循環
通過任意提供的迭代器的對象循環(迭代器與java類似):
for (item in collection)
print(item)
遍歷數組:
var types = intArrayOf(1, 2, 3)
for(index in types.indices)
print(index.toString() + " ")
for((index, value ) in types.withIndex())
println("index: $index, value: $value")
while循環
跟平常的while使用一樣:
var index = 0
while(index < 10)
print(index++)
index = 0
do{
print(index)
}while (index++ < 10)