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

相关推荐
01漫游者4 分钟前
JavaScript函数与对象增强知识
开发语言·javascript·ecmascript
IGAn CTOU5 分钟前
Java高级开发进阶教程之系列
java·开发语言
csbysj202011 分钟前
SQL NULL 函数详解
开发语言
其实防守也摸鱼14 分钟前
CTF密码学综合教学指南--第三章
开发语言·网络·python·安全·网络安全·密码学
NGSI vimp15 分钟前
Java进阶——如何查看Java字节码
java·开发语言
We་ct1 小时前
深度剖析浏览器跨域问题
开发语言·前端·浏览器·跨域·cors·同源·浏览器跨域
skywalk81631 小时前
在考虑双轨制,即在中文语法的基础上,加上数学公式的支持,这样像很多计算将更加简单方便,就像现在的小学数学课本里面一样,比如:定x=2*x + 1
开发语言
小书房1 小时前
Kotlin的by
android·开发语言·kotlin·委托·by
就叫飞六吧2 小时前
QT写一个桌面程序exe并动态打包基本流程(c++)
开发语言·c++
threelab2 小时前
Three.js 代码云效果 | 三维可视化 / AI 提示词
开发语言·javascript·人工智能