前言
隨着越來越多的開發者將Kotlin運用到自己的項目中,使用Kotlin開發Android應用,已逐漸成爲一種趨勢。因此瞭解並掌握Kotlin語言,勢在必行。
現將本人學習Kotlin的過程記錄如下,以備回顧、參照。
學習資源:
Kotlin語言中文站: https://www.kotlincn.net/
菜鳥課堂: https://www.runoob.com/kotlin/kotlin-tutorial.html
一、基礎:
1、可以使用下劃線使數字常量更易讀
如:val oneMillion = 1_000_000
2、數值變量會有一個自動裝箱的過程,數字裝箱不一定保留同一性。所以兩個等號邏輯判斷兩個變量的數值相等性,三個等號還同時比較類型的同一性。
val a: Int = 10000
val boxedA: Int? = a
val anotherBoxedA: Int? = a
println(a == a) // 輸出“true”
println(boxedA == anotherBoxedA) // 輸出“true”
//========但是========
println(a === a) // 輸出“true”
println(boxedA === anotherBoxedA) // !!!輸出“false”!!!
3、基礎數據類型中,較小的類型不能隱式轉換爲較大的類型。 這意味着在不進行顯式轉換的情況下我們不能把 Byte 型值賦給一個 Int 變量。
val b: Byte = 1 // OK, 字面值是靜態檢測的
val i: Int = b // 錯誤
val i: Int = b.toInt() // OK:顯式拓寬
print(i)// 輸出1
4、控制流
If表達式
在 Kotlin 中,if是一個表達式,即它會返回一個值。 因此就不需要三元運算符(條件 ? 然後 : 否則),因爲普通的 if 就能勝任這個角色。
var max = a
if (a < b) max = b
// With else
var max: Int
if (a > b) {
max = a
} else {
max = b
}
// 作爲表達式
val max = if (a > b) a else b
When表達式
when 將它的參數與所有的分支條件順序比較,直到某個分支滿足條件。
when (x) {
1 -> print("x == 1")
2 -> print("x == 2")
else -> { // 注意這個塊
print("x is neither 1 nor 2")
}
}
when 也可以用來取代 if-else if鏈。 如果不提供參數,所有的分支條件都是簡單的布爾表達式,而當一個分支的條件爲真時則執行該分支
when {
x.isOdd() -> print("x is odd")
x.isEven() -> print("x is even")
else -> print("x is funny")
}
For循環
for (i in 1..3) {
println(i)
}
for (i in 6 downTo 0 step 2) {
println(i)
}
for (i in array.indices) {
println(array[i])
}
for ((index, value) in array.withIndex()) {
println("the element at $index is $value")
}
While循環
與java 相同,while 與 do…while 照常使用
while (x > 0) {
x--
}
do {
val y = retrieveData()
} while (y != null) // y 在此處可見
Return的區別
1)fun foo() {
listOf(1, 2, 3, 4, 5).forEach {
if (it == 3) return // 非局部直接返回到 foo() 的調用者
println(it)
}
print("this point is unreachable")
}
// 結果返回:12
2)fun foo() {
listOf(1, 2, 3, 4, 5).forEach a@{
if (it == 3) return@a // 局部返回到該 lambda 表達式的調用者,即 forEach 循環
println(it)
}
print(" done with explicit label")
}
3)fun foo() {
listOf(1, 2, 3, 4, 5).forEach {
if (it == 3) return@forEach // 局部返回到該 lambda 表達式的調用者,即 forEach 循環
print(it)
}
print(" done with implicit label")
}
4)fun foo() {
listOf(1, 2, 3, 4, 5).forEach(fun(value: Int) {
if (value == 3) return // 局部返回到匿名函數的調用者,即 forEach 循環
print(value)
})
print(" done with anonymous function")
}
/*以上2)、3)4)三種寫法均返回:1245 done with anonymous function
這三種寫法中使用的局部返回類似於在常規循環中使用 continue。並沒有 break 的直接等價形式,我們可以通過增加另一層嵌套 lambda 表達式並從其中非局部返回來模擬*/
5)fun foo() {
run loop@{
listOf(1, 2, 3, 4, 5).forEach {
if (it == 3) return@loop // 從傳入 run 的 lambda 表達式非局部返回
print(it)
}
}
print(" done with nested loop")
}
// 此時返回:12 done with nested loop