Lambda Expressions trong Kotlin
1. Giới thiệu
Lambda là anonymous function có thể lưu vào biến và truyền như parameter.
2. Cú pháp cơ bản
fun main() {
// Cú pháp đầy đủ
val sum: (Int, Int) -> Int = { a: Int, b: Int -> a + b }
// Type inference
val multiply = { a: Int, b: Int -> a * b }
println(sum(5, 3)) // 8
println(multiply(4, 2)) // 8
}3. Lambda với it
fun main() {
// Single parameter -> dùng it
val double = { it: Int -> it * 2 }
// Với type inference
val list = listOf(1, 2, 3)
val doubled = list.map { it * 2 }
println(doubled) // [2, 4, 6]
}4. Trailing Lambda
fun main() {
val list = listOf(1, 2, 3, 4, 5)
// Lambda là parameter cuối -> để ngoài ()
val evens = list.filter { it % 2 == 0 }
// Tương đương
val evens2 = list.filter({ it % 2 == 0 })
println(evens) // [2, 4]
}5. Lambda với Collections
fun main() {
val numbers = listOf(1, 2, 3, 4, 5)
// map
numbers.map { it * 2 }
// filter
numbers.filter { it > 2 }
// forEach
numbers.forEach { println(it) }
// reduce
numbers.reduce { acc, n -> acc + n }
// any / all
numbers.any { it > 3 }
numbers.all { it > 0 }
}6. Lambda với return
fun main() {
val list = listOf(1, 2, 3, 4, 5)
// Return từ lambda
list.forEach {
if (it == 3) return@forEach // Continue
println(it)
}
// Labeled return
list.forEach label@{
if (it == 3) return@label
println(it)
}
}7. Destructuring trong Lambda
fun main() {
val map = mapOf("a" to 1, "b" to 2)
map.forEach { (key, value) ->
println("$key -> $value")
}
val pairs = listOf(1 to "one", 2 to "two")
pairs.forEach { (num, name) ->
println("$num is $name")
}
}8. Lambda với Receiver
fun main() {
// Lambda with receiver
val greet: String.() -> String = { "Hello, $this!" }
println("World".greet()) // Hello, World!
// Trong builder pattern
val html = buildString {
append("<html>")
append("<body>Hello</body>")
append("</html>")
}
}9. Inline Lambda
inline fun performOperation(a: Int, b: Int, operation: (Int, Int) -> Int): Int {
return operation(a, b)
}
fun main() {
val result = performOperation(5, 3) { x, y -> x + y }
println(result) // 8
}10. Ví dụ thực tế
data class Person(val name: String, val age: Int)
fun main() {
val people = listOf(
Person("Alice", 25),
Person("Bob", 30),
Person("Charlie", 20)
)
// Chain operations
val names = people
.filter { it.age >= 25 }
.sortedBy { it.name }
.map { it.name }
println(names) // [Alice, Bob]
}📝 Tóm tắt
- Lambda:
{ params -> body } - Single param dùng
it - Trailing lambda syntax
return@labelcho local return- Destructuring trong lambda
- Lambda with receiver:
Type.() -> R
Last updated on