if的使用
fun ifExpression(): Int{
//1.最普通的寫法
var max: Int
if (a < b) {
max = b
}
else{
max = a
}
return max
}
val max = if(a > b) a else b
如果if語句下由多個語句,那麼最後一行是其結果
val max2 = if(a > b){
println("a > b")
a
}else{
println("a < b")
b
}
when表達式
普通的寫法
fun whenExpression(x: Int) {
when(x){
1 -> println("x == 1")
2 -> println("x == 2")
else -> {
print("x is neither 1 nor 2")
}
}
}
多個case有同一種處理方式的話,可以通過逗號連接
when(x){
1, 2 -> println("x == 1 or x == 2")
else -> println("x is neither 1 nor 2")
}
如果case在一定的範圍內有相同的處理方式
when(x){
in 1..10 -> println("x在1到10的範圍內")
!in 10..20 -> println("x不在10到20的範圍內")
else -> println("none of the above")
}
如果case是一個表達式,可以這麼寫
when(x){
parseInt(s) -> println("s encodes x")
else -> println("s does not encode x")
}
for循環
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循環的使用有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!
}
流程控制部分的詳細內容可以傳送到官方文檔
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
運算符部分的詳細內容可以傳送到官方文檔