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. 使用作用域函数让代码更清晰

相关推荐
AI360labs_atyun25 分钟前
Java在AI时代的演进与应用:一个务实的视角
java·开发语言·人工智能·科技·学习·ai
wuwu_q1 小时前
RK3566/RK3568 Android11 修改selinux模式
android·rk3568
凤年徐1 小时前
【数据结构与算法】203.移除链表元素(LeetCode)图文详解
c语言·开发语言·数据结构·算法·leetcode·链表·刷题
_一条咸鱼_1 小时前
Android Runtime内存共享与访问控制原理剖析(71)
android·面试·android jetpack
nbsaas-boot2 小时前
多租户架构下的多线程处理实践指南
java·开发语言·spring
嘉小华2 小时前
第三章:焦点分发全链路源码解析
android
嘉小华2 小时前
Android 协程全景式深度解析:第六章 高阶并发模式
android
无小道2 小时前
c++--typedef和#define的用法及区别
c语言·开发语言·汇编·c++
嘉小华2 小时前
Android 协程全景式深度解析:第七章 协程调试与性能优化
android
你过来啊你2 小时前
Android开发中RxJava的使用与原理
android