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

相关推荐
odoo中国17 分钟前
Odoo 19 模块结构概述
开发语言·python·module·odoo·核心组件·py文件按
遥不可及zzz25 分钟前
Android 接入UMP
android
代码N年归来仍是新手村成员1 小时前
【Java转Go】即时通信系统代码分析(一)基础Server 构建
java·开发语言·golang
Z1Jxxx1 小时前
01序列01序列
开发语言·c++·算法
沐知全栈开发2 小时前
C语言中的强制类型转换
开发语言
关于不上作者榜就原神启动那件事2 小时前
Java中大量数据Excel导入导出的实现方案
java·开发语言·excel
坚定学代码2 小时前
基于观察者模式的ISO C++信号槽实现
开发语言·c++·观察者模式·ai
Wang's Blog2 小时前
Nodejs-HardCore: Buffer操作、Base64编码与zlib压缩实战
开发语言·nodejs
Coder_Boy_2 小时前
基于SpringAI的在线考试系统设计总案-知识点管理模块详细设计
android·java·javascript
csbysj20202 小时前
C# 集合(Collection)
开发语言