if-else表達式的使用,最普通的寫法以下html
fun ifExpression(): Int{
//1.最普通的寫法
var max: Int
if (a < b) {
max = b
}
else{
max = a
}
return max
}
複製代碼
在Kotlin能夠將上面的栗子寫成if表達式的形式java
val max = if(a > b) a else b
複製代碼
注意:表達式必定要完整,不能省略else部分數組
若是if表達式某個條件下有多個語句,那麼最後一行是其返回結果bash
val max2 = if(a > b){
println("a > b")
a
}else{
println("a < b")
b
}
複製代碼
when和java中的switch功能是同樣的,switch能實現的,when均可以實現,而且寫起來更簡潔ide
when表達式的普通的寫法,舉個栗子函數
fun whenExpression(x: Int) {
when(x){
1 -> println("x == 1")
2 -> println("x == 2")
else -> {
print("x is neither 1 nor 2")
}
}
}
複製代碼
when下的語句,若是其中一條符合條件,就會直接跳出並返回結果oop
若是多個case有同一種處理方式的話,能夠經過逗號鏈接,譬如這樣:ui
when(x){
1, 2 -> println("x == 1 or x == 2")
else -> println("x is neither 1 nor 2")
}
複製代碼
那若是case在必定的範圍內有相同的處理方式呢?能夠這樣寫:spa
when(x){
in 1..10 -> println("x在1到10的範圍內")
!in 10..20 -> println("x不在10到20的範圍內")
else -> println("none of the above")
}
複製代碼
那若是case是一個表達式,就能夠這麼寫:code
when(x){
parseInt(s) -> println("s encodes x")
else -> println("s does not encode x")
}
複製代碼
for循環遍歷範圍內的數
for(i in 1..10) println(i)
複製代碼
downTo 從6降到0 step 步長爲2
for(i in 6 downTo 0 step 2) println(i)
複製代碼
for循環遍歷一個數組
var array: Array<String> = arrayOf("I","am","jason","king")
//迭代一個數組
for(i in array.indices){
print(array[i])
}
複製代碼
遍歷數組,輸出對應下標的值
for((index,value) in array.withIndex()){
println("該數組下標$index 的元素是這個$value")
}
複製代碼
while循環的使用有while 和 do-while兩種方式
fun whileLoop() {
var x = 5
//while
while (x > 0){
x--
print("$x-->")
}
x = 5
println()
do {
x--
print("$x-->")
} while (x >= 0) // y is visible here!
}
複製代碼
跳出循環break和跳過循環continue和其餘語言語法徹底同樣,這裏就不贅述了。
流程控制部分的詳細內容傳送到這裏
Control Flow 流程控制部分的詳細內容能夠傳送到官方文檔 Control Flow
Kotlin中任何類能夠定義或重載父類的基本運算符,須要用operator關鍵字
舉個栗子,對Complex類重載 + 運算符
class Complex(var real: Double,var imaginary: Double){
//重載加法運算符
operator fun plus(other: Complex): Complex {
return Complex(real + other.real,imaginary + other.imaginary)
}
//重寫toString輸出
override fun toString(): String {
return "$real + $imaginary"
}
}
複製代碼
在main函數使用重載的 + 運算符
var c1 = Complex(1.0,2.0)
var c2 = Complex(2.0,3.0)
println(c1 + c2)
複製代碼
輸出結果
3.0 + 5.0
運算符部分的詳細內容能夠傳送到官方文檔