补充 Kotlin 进阶细节与成为超人篇内容

This commit is contained in:
SOR2171
2026-10-10 09:15:42 +08:00
parent 46b2b8f44e
commit 4b0f0d80b6
9 changed files with 280 additions and 13 deletions
+45 -1
View File
@@ -886,7 +886,7 @@ println("是否为可变长参数: ${param.isVararg}")
## 定义一个特殊的变量/函数名
只需要使用反引号 ``` ` ``` 将一个任意符串包裹起来,它几乎可以被定义为所有东西的名称。
只需要使用反引号 ``` ` ``` 将一个任意字符串包裹起来,它几乎可以被定义为任何东西的名称。
```kotlin
fun `fun`() = "fun" // 例如定义一个函数
@@ -894,6 +894,50 @@ val `this` = 1 // 或是一个变量
val `or write a sentence` = true
```
## 类型别名 typealias
当某些类型名字特别长,或者某些 lambda 函数类型签名较长时,写起来会很啰嗦。使用 `typealias` 可以给现有类型起一个简单易读的别名。
```kotlin
// 给复杂的函数类型起别名
typealias ClickListener = (viewId: Int, message: String) -> Unit
fun setOnClick(listener: ClickListener) {
listener(1, "clicked")
}
// 给长泛型起别名
typealias UserMap = Map<String, List<Set<Int>>>
// 在 KMP 中非常关键:直接将平台已有类型映射给 commonMain 的公共声明
expect class AtomicInt
actual typealias AtomicInt = java.util.concurrent.atomic.AtomicInteger
```
## Nothing 类型与 TODO()
在 Kotlin 中,`Nothing` 是一个非常特殊的底层类型:它是**所有其他类型的子类型(Bottom type)**。
它表示“这个函数永远不会正常返回”,比如抛出异常或者死循环的函数:
```kotlin
fun fail(message: String): Nothing {
throw IllegalArgumentException(message)
}
```
因为 `Nothing` 是所有类型的子类,所以在类型推断和空安全配合时非常方便:
```kotlin
// 1. Elvis 操作符配合抛异常,编译器会自动把 Noting 识别为非空 String
val name: String = inputName ?: fail("Name is required")
// 2. TODO() 占位
fun calculateComplexLogic(): Int {
TODO("还没写完,占个位编译不报错") // TODO() 的返回值就是 Nothing
}
```
## IDEA 的常用快捷键
`ctrl + alt + L`:格式化代码