11月16日 JetBrains 正式發(fā)布了 Kotlin 1.6.0,這個(gè)版本根據(jù)一些反饋,將上一版本中的一些實(shí)驗(yàn)的語法特性進(jìn)行了轉(zhuǎn)正。例如
- Sealed exhaustive whens
- Suspending functions as supertypes
- ...
Sealed exhaustive whens
當(dāng)我們在 when 中使用諸如枚舉、密封類/接口等可窮舉類型時(shí),某些情況下可能寫出不安全的代碼
sealed class Contact { data class PhoneCall(val number: String) : Contact() data class TextMessage(val number: String) : Contact() data class InstantMessage(val type: IMType, val user: String) : Contact()}復(fù)制代碼
如上,定義了三個(gè)子類的密封類
fun Rates.computeMessageCost(contact: Contact): Cost = when (contact) { // ERROR: when expression must be exhaustive is Contact.PhoneCall -> phoneCallCost is Contact.TextMessage -> textMessageCost }復(fù)制代碼
此時(shí)如果 case 后跟的是一個(gè)表達(dá)式, 則如果 case 分支沒有窮舉所有子類,編譯器會報(bào)錯(cuò)
但是如果如果 case 后個(gè)的是一個(gè)語句,如下
fun sendAnnouncement(contact: Contact, announcement: Announcement) { when (contact) { is Contact.PhoneCall -> schedulePhoneCall(contact.number, announcement) is Contact.TextMessage -> sendTextMessage(contact.number, announcement) }}復(fù)制代碼
此時(shí)即使沒有窮舉所有子類,編譯器也不會報(bào)錯(cuò),這可能會造成不必要的bug
Kotlin 1.6 在這種情況下,編譯器會給出 Warning ,按計(jì)劃 1.7 之后 Warning 會改為 Error,強(qiáng)制開發(fā)者補(bǔ)齊所有分支邏輯,避免出現(xiàn) Bug
Suspending functions as supertypes
Kotlin 中許多 API 都以函數(shù)類型作為參數(shù)。當(dāng)你需要調(diào)用這些 API 時(shí),需要傳入一個(gè)函數(shù)類型的實(shí)例。而當(dāng)你想在實(shí)例中封裝一些可復(fù)用的邏輯時(shí),可以使用函數(shù)類型作為父類創(chuàng)建子類。
但是這種做法目前不適用于掛起函數(shù),你無法繼承一個(gè) suspend
函數(shù)類型的父類
class C : suspend () -> Unit { // Error: Suspend function type is not allowed as supertypes }C().startCoroutine(completion = object : Continuation<Unit> { override val context: CoroutineContext get() = TODO("Not yet implemented") override fun resumeWith(result: Result<Unit>) { TODO("Not yet implemented") }})復(fù)制代碼
Kotlin 1.5.30 在 Preveiw 中引入了此特性,可以繼承一個(gè) suspend 的函數(shù)類型
class MyClickAction : suspend () -> Unit { override suspend fun invoke() { TODO() }}fun launchOnClick(action: suspend () -> Unit) {}復(fù)制代碼
如上,你現(xiàn)在可以這樣調(diào)用 launchOnClick(MyClickAction())
。
1.6 中將此 feature 默認(rèn)打開。
此外 1.6 還加入了其他一些新的語法特性,詳情可以參考:blog.jetbrains.com/kotlin/2021…
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請注明本文地址:http://www.ezyhdfw.cn/yun/123972.html