目录
- 函数进阶:默认参数与命名参数
- 高阶函数与Lambda表达式
- 扩展函数与扩展属性
- 数据类(data class)
- 密封类(sealed class)
- 泛型基础
1️⃣ 函数进阶:默认参数与命名参数
- Kotlin支持函数参数默认值,调用时可省略参数。
- 调用时可用命名参数明确传递,增加代码可读性。
fun greet(name: String = "World", punctuation: String = "!") {
println("Hello, $name$punctuation")
}
greet() // Hello, World!
greet("Kotlin") // Hello, Kotlin!
greet(punctuation = "?") // Hello, World?
greet(name = "Alice", punctuation = ".") // Hello, Alice.
2️⃣ 高阶函数与Lambda表达式
- 高阶函数:参数或返回值为函数的函数。
- Lambda表达式:匿名函数简写,方便传递代码块。
fun operateOnNumbers(a: Int, b: Int, operation: (Int, Int) -> Int): Int {
return operation(a, b)
}
val sum = operateOnNumbers(3, 4) { x, y -> x + y }
println(sum) // 7
3️⃣ 扩展函数与扩展属性
- 给已有类添加新函数或属性,无需继承,增强代码灵活性。
fun String.addExclamation(): String {
return this + "!"
}
println("Hello".addExclamation()) // Hello!
4️⃣ 数据类(data class)
- 用于存储数据的类,自动生成equals、hashCode、toString、copy等函数。
data class User(val name: String, val age: Int)
val user1 = User("Bob", 25)
val user2 = user1.copy(age = 26)
println(user1) // User(name=Bob, age=25)
println(user2) // User(name=Bob, age=26)
5️⃣ 密封类(sealed class)
- 用于表示有限的类型集合,通常用来代替枚举,支持继承。
sealed class Result
data class Success(val data: String): Result()
data class Error(val error: Throwable): Result()
fun handleResult(result: Result) {
when(result) {
is Success -> println("Success: ${result.data}")
is Error -> println("Error: ${result.error.message}")
}
}
6️⃣ 泛型基础
class Box<T>(val value: T)
val intBox = Box(123)
val stringBox = Box("Kotlin")
println(intBox.value) // 123
println(stringBox.value) // Kotlin
发表回复