Kotlin / Java 的比較
以下開始記錄 Kotlin 的優點 (與 Java 比較) :https://www.androidauthority.com/kotlin-vs-java-783187/
1. 比較簡潔(concise)。
如 UI 的 findViewById,Kotlin 可直接存取 ui compoent)
2. default null safe。
Kotlin 變數預設是不允許為 null (Java 是),如果要直接設成 null,要使用 "?=" 設給 l-value。
3. Extension functions。
4. Coroutines (Kotlin 導入 suspend 概念,此詞意同 non-blocking 機制,相仿 thread sleep )
Kotlin 支援 async/await (同 C# async/await)
// non-blocking coroutine
val job = launch {
delay(1000L)// delay 是 suspend 的 sleep
}
// blocking coroutine
runBlocking {
delay(1000L)
}
* life cycle
GlobalScope.lauch 的 GlobalScope 是指整個 app 存在時,此 coroutine 就會存在。也可自 訂 coroutine 的 life cycle。
* 在 coroutine block 中呼叫 func 時,要使用 suspend 修飾字放在 func 前,才能被 corouine 使用。
* coroutine 的 func : join、cancel、cancelAndJoin
* timeout
withTimeout(1300L) { //withTimeoutOrNull() 則是可以回傳 null
repeat(1000) { i ->
println("I'm sleeping $i ...")
delay(500L)
}
}
5. 支援 default function parameter (Java 不支援,需要以 function overload 達成)
支援 properties (Java 沒有,C# 有)
頁:
[1]