Extension Functions trong Kotlin
1. Giới thiệu
Extension functions cho phép thêm methods mới vào class có sẵn mà không cần kế thừa.
2. Cú pháp cơ bản
fun String.addExclamation(): String {
return "$this!"
}
fun main() {
val greeting = "Hello"
println(greeting.addExclamation()) // Hello!
}3. Extension cho Int
fun Int.isEven() = this % 2 == 0
fun Int.isOdd() = this % 2 != 0
fun Int.squared() = this * this
fun main() {
println(4.isEven()) // true
println(5.squared()) // 25
}4. Extension cho List
fun <T> List<T>.secondOrNull(): T? {
return if (size >= 2) this[1] else null
}
fun List<Int>.sumOfSquares(): Int {
return this.sumOf { it * it }
}
fun main() {
val list = listOf(1, 2, 3)
println(list.secondOrNull()) // 2
println(list.sumOfSquares()) // 14
}5. Extension Properties
val String.firstChar: Char?
get() = this.firstOrNull()
val <T> List<T>.lastIndex: Int
get() = this.size - 1
fun main() {
println("Hello".firstChar) // H
println(listOf(1, 2, 3).lastIndex) // 2
}6. Nullable Receiver
fun String?.orEmpty(): String {
return this ?: ""
}
fun main() {
val name: String? = null
println(name.orEmpty()) // "" (empty string)
}7. Extension trong Object/Companion
class MyClass {
companion object
}
fun MyClass.Companion.create(): MyClass {
return MyClass()
}
fun main() {
val instance = MyClass.create()
}8. Generic Extensions
fun <T> T.toSingletonList(): List<T> = listOf(this)
fun <T : Comparable<T>> T.coerceIn(min: T, max: T): T {
return when {
this < min -> min
this > max -> max
else -> this
}
}
fun main() {
println(5.toSingletonList()) // [5]
println(10.coerceIn(1, 5)) // 5
}9. Scope Functions là Extensions
fun main() {
val result = StringBuilder().apply {
append("Hello")
append(" ")
append("World")
}.toString()
println(result) // Hello World
val length = "Kotlin".let { it.length }
println(length) // 6
}10. Best Practices
// ✅ Đặt extensions trong file riêng
// StringExtensions.kt
fun String.removeWhitespace() = this.replace(" ", "")
// ✅ Dùng cho utility functions
fun LocalDate.isWeekend() =
dayOfWeek == DayOfWeek.SATURDAY || dayOfWeek == DayOfWeek.SUNDAY
// ❌ Tránh thay đổi behavior cốt lõi
// fun Int.plus(other: Int) = this - other // Confusing!📝 Tóm tắt
fun Type.functionName()để tạo extensionthistham chiếu đến receiver object- Extension properties chỉ có getter (không có backing field)
- Nullable receiver với
Type? - Không override member functions
- Thêm functionality mà không cần kế thừa
Last updated on