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 代码更简洁、更安全、更易读。
主要优势:
-
**空安全**:避免空指针异常
-
**函数式编程**:更简洁的集合操作
-
**扩展函数**:为现有类添加功能
-
**数据类**:自动生成常用方法
-
**协程**:简化异步编程
-
**委托属性**:减少样板代码
-
**作用域函数**:更清晰的代码结构
使用建议:
-
优先使用 Kotlin 的语法糖,减少样板代码
-
合理使用空安全操作符,避免空指针异常
-
善用扩展函数,提高代码可读性
-
使用数据类简化模型类
-
利用协程简化异步编程
-
使用作用域函数让代码更清晰