Kotlin 常用语法糖完整整理

Kotlin 实用语法糖整理

1. 属性访问

复制代码
class Person {
    var name: String = ""  // 自动生成 getter/setter
    val age: Int = 25      // 只读属性,仅生成 getter
}

2. 空安全操作

复制代码
val length = name?.length        // 安全调用
val length = name?.length ?: 0   // 空值替代
val length = name!!.length       // 强制非空

3. 字符串模板

复制代码
val name = "Kotlin"
val message = "Hello, $name!"            // 变量引用
val message2 = "Length: ${name.length}"  // 表达式引用

4. 集合操作

复制代码
val numbers = listOf(1, 2, 3, 4, 5)
val doubled = numbers.map { it * 2 }     // 映射
val evens = numbers.filter { it % 2 == 0 } // 过滤
val sum = numbers.reduce { acc, num -> acc + num } // 归约
val first = numbers.find { it > 3 }      // 查找首个
val exists = numbers.any { it > 3 }      // 存在性检查
val all = numbers.all { it > 0 }         // 全量检查

5. 扩展函数

复制代码
fun String.addExclamation() = "$this!"
val result = "Hello".addExclamation()  // 输出: "Hello!"

6. 数据类

复制代码
data class Person(val name: String, val age: Int)
val person = Person("Alice", 25)
val copy = person.copy(age = 26)  // 复制修改

7. 智能类型转换

复制代码
fun demo(x: Any) {
    if (x is String) {
        println(x.length)  // 自动转为String
    }
}

8. when表达式

复制代码
val result = when (x) {
    1 -> "One"
    2 -> "Two"
    else -> "Other"
}

val status = when {
    age < 18 -> "未成年"
    age < 60 -> "成年"
    else -> "老年"
}

9. 解构声明

复制代码
val (name, age) = Person("Alice", 25)
for ((k, v) in map) {
    println("$k: $v")
}

10. Lambda表达式

复制代码
val sum = { x: Int, y: Int -> x + y }
list.forEach { println(it) }
with(person) {
    println(name)
    println(age)
}

11. 作用域函数

复制代码
person.let { println(it.name) }  // let
with(person) { println(name) }   // with
person.apply { name = "Bob" }    // apply
person.run { "$name is $age" }   // run

12. 集合链式操作

复制代码
val result = list
    .filter { it > 2 }
    .map { it * 2 }
    .take(2)
    .sum()

13. 参数默认值

复制代码
fun greet(name: String, greeting: String = "Hello") {
    println("$greeting, $name!")
}
greet("Alice")                    // 默认参数
greet("Bob", greeting = "Hi")     // 命名参数

14. 单例与伴生对象

复制代码
object Singleton {
    fun action() = "Hello"
}

class MyClass {
    companion object {
        fun create() = MyClass()
    }
}

15. 属性委托

复制代码
class Example {
    var p: String by Delegate()
    val lazyVal by lazy { "计算值" }
}

16. 内联函数

复制代码
inline fun measureTime(action: () -> Unit): Long {
    val start = System.currentTimeMillis()
    action()
    return System.currentTimeMillis() - start
}

17. 密封类

复制代码
sealed class Result {
    data class Success(val data: String) : Result()
    data class Error(val msg: String) : Result()
}

18. 协程基础

复制代码
suspend fun fetchData(): String {
    delay(1000)
    return "数据"
}

CoroutineScope(Dispatchers.IO).launch {
    val data = fetchData()
    withContext(Dispatchers.Main) {
        updateUI(data)
    }
}

19. 委托实现

复制代码
class Delegate {
    private var value = ""
    
    operator fun getValue(thisRef: Any?, prop: KProperty<*>): String = value
    operator fun setValue(thisRef: Any?, prop: KProperty<*>, newValue: String) {
        value = newValue
    }
}

20. 运算符重载

复制代码
data class Point(val x: Int, val y: Int) {
    operator fun plus(other: Point) = Point(x + other.x, y + other.y)
}
val p = Point(1, 2) + Point(3, 4)  // Point(4, 6)

21. 中缀表达式

复制代码
infix fun Int.times(str: String) = str.repeat(this)
val res = 3 times "Hi "  // "Hi Hi Hi "

22. 尾递归优化

复制代码
tailrec fun factorial(n: Int, acc: Int = 1): Int {
    return if (n <= 1) acc else factorial(n - 1, n * acc)
}

23. 类型别名

复制代码
typealias StringList = List<String>
typealias Predicate<T> = (T) -> Boolean

24. 内联类

复制代码
inline class Password(val value: String) {
    fun isValid() = value.length >= 8
}

25. 协程作用域

复制代码
runBlocking {
    delay(1000)
    println("完成")
}

suspend fun fetch() = coroutineScope {
    val d1 = async { fetch1() }
    val d2 = async { fetch2() }
    d1.await() + d2.await()
}

26. 集合构建

复制代码
val list = buildList {
    add("第一项")
    add("第二项")
    addAll(listOf("第三", "第四"))
}

27. 序列操作

复制代码
val seq = sequence {
    yield(1)
    yield(2)
    yield(3)
}

28. 反射注解

复制代码
@Target(AnnotationTarget.CLASS)
@Retention(AnnotationRetention.RUNTIME)
annotation class MyAnnotation(val value: String)

29. DSL构建

复制代码
class HTMLBuilder {
    fun head(init: Head.() -> Unit) = Head().apply(init)
}

29. DSL (领域特定语言)

复制代码
class HTMLBuilder {
    fun head(init: Head.() -> Unit) = Head().apply(init)
    fun body(init: Body.() -> Unit) = Body().apply(init)
}

30. 委托属性 - 内置实现

复制代码
class Example {
    val lazyValue: String by lazy { "耗时计算" }
    
    var name: String by Delegates.observable("") { 
        _, old, new ->
        println("$old -> $new")
    }
    
    var age: Int by Delegates.vetoable(0) { 
        _, _, new ->
        new >= 0
    }
}

31. 扩展属性

复制代码
val String.lastChar: Char
    get() = this[length - 1]

val String.isPalindrome: Boolean
    get() = this == reversed()

32. 高阶函数与函数类型

复制代码
typealias Operation = (Int, Int) -> Int

fun calculate(a: Int, b: Int, operation: Operation) = operation(a, b)

val add: Operation = { a, b -> a + b }
val result = calculate(5, 3, add)  // 8

33. 协程通道

复制代码
fun CoroutineScope.produceNumbers() = produce<Int> {
    repeat(5) { x ->
        send(x + 1)
    }
}

34. 内联函数与具体化类型

复制代码
inline fun <reified T> createInstance() = 
    T::class.java.getDeclaredConstructor().newInstance()

35. 集合扩展函数

复制代码
val list = listOf(1, 2, 3, 4, 5)
list.isNotEmpty()      // true
list.isEmpty()         // false
list.all { it > 0 }    // true
list.any { it > 3 }    // true
list.none { it > 10 }  // true
list.count { it % 2 == 0 } // 2

36. 字符串扩展函数

复制代码
val text = "  Hello World  "
text.trim()            // "Hello World"
text.isBlank()         // false
text.isNotBlank()      // true
text.uppercase()       // "  HELLO WORLD  "
text.lowercase()       // "  hello world  "

37. 集合分组操作

复制代码
val list = listOf(1, 2, 3, 4, 5)
val grouped = list.groupBy { it % 2 == 0 }
val (even, odd) = list.partition { it % 2 == 0 }

38. 集合类型转换

复制代码
val list = listOf(1, 2, 3, 4, 5)
list.toSet()           // Set<Int>
list.associate { it to it * 2 } // {1=2, 2=4, 3=6, 4=8, 5=10}

39. 集合查询操作

复制代码
val list = listOf(1, 2, 3, 4, 5)
list.find { it > 3 }    // 4
list.firstOrNull { it > 3 } // 4
list.random()           // 随机元素

40. 集合排序去重

复制代码
val list = listOf(3, 1, 4, 1, 5, 9, 2, 6)
list.sorted()          // [1, 1, 2, 3, 4, 5, 6, 9]
list.distinct()        // [3, 1, 4, 5, 9, 2, 6]

41. 集合窗口操作

复制代码
val list = listOf(1, 2, 3, 4, 5)
list.windowed(3)       // [[1, 2, 3], [2, 3, 4], [3, 4, 5]]
list.chunked(2)        // [[1, 2], [3, 4], [5]]

42. 集合聚合操作

复制代码
val list = listOf(1, 2, 3, 4, 5)
list.sum()             // 15
list.average()         // 3.0
list.minOrNull()       // 1
list.maxOrNull()       // 5

43. 字符串操作扩展

复制代码
val text = "Hello World"
text.first()           // 'H'
text.last()            // 'd'
text.substring(0, 5)   // "Hello"
text.replace("World", "Kotlin") // "Hello Kotlin"

44. 集合比较操作

复制代码
val list1 = listOf(1, 2, 3)
val list2 = listOf(1, 2, 3)
list1 == list2         // true
list1.contentEquals(list2) // true

总结

这就是 Kotlin 最常用的语法糖完整整理!这些特性让 Kotlin 代码更简洁、更安全、更易读。

主要优势:

  • **空安全**:避免空指针异常

  • **函数式编程**:更简洁的集合操作

  • **扩展函数**:为现有类添加功能

  • **数据类**:自动生成常用方法

  • **协程**:简化异步编程

  • **委托属性**:减少样板代码

  • **作用域函数**:更清晰的代码结构

使用建议:

  1. 优先使用 Kotlin 的语法糖,减少样板代码

  2. 合理使用空安全操作符,避免空指针异常

  3. 善用扩展函数,提高代码可读性

  4. 使用数据类简化模型类

  5. 利用协程简化异步编程

  6. 使用作用域函数让代码更清晰

相关推荐
阿巴斯甜12 小时前
Android 报错:Zip file '/Users/lyy/develop/repoAndroidLapp/l-app-android-ble/app/bu
android
Kapaseker13 小时前
实战 Compose 中的 IntrinsicSize
android·kotlin
xq952714 小时前
Andorid Google 登录接入文档
android
黄林晴15 小时前
告别 Modifier 地狱,Compose 样式系统要变天了
android·android jetpack
冬奇Lab1 天前
Android触摸事件分发、手势识别与输入优化实战
android·源码阅读
城东米粉儿1 天前
Android MediaPlayer 笔记
android
Jony_1 天前
Android 启动优化方案
android
阿巴斯甜1 天前
Android studio 报错:Cause: error=86, Bad CPU type in executable
android
张小潇1 天前
AOSP15 Input专题InputReader源码分析
android
_小马快跑_1 天前
Kotlin | 协程调度器选择:何时用CoroutineScope配置,何时用launch指定?
android