Extension Functions trong Kotlin
🎯 Mục tiêu: Hiểu Extension Functions - thêm method cho class có sẵn mà không cần kế thừa.
💡 Khái niệm
Extension function cho phép “thêm” method vào class đã tồn tại.
fun String.addExclamation() = "$this!"
fun main() {
println("Hello".addExclamation()) // Hello!
}📝 Cú pháp
fun ReceiverType.functionName(params): ReturnType {
// `this` là receiver object
return this.doSomething()
}🔧 Ví dụ thực tế
// String extensions
fun String.isEmail() = contains("@") && contains(".")
fun String.toTitleCase() = split(" ").joinToString(" ") {
it.lowercase().replaceFirstChar { c -> c.uppercase() }
}
// Int extensions
fun Int.isEven() = this % 2 == 0
fun Int.squared() = this * this
// List extensions
fun <T> List<T>.secondOrNull() = getOrNull(1)
fun main() {
println("[email protected]".isEmail()) // true
println("hello world".toTitleCase()) // Hello World
println(5.isEven()) // false
println(4.squared()) // 16
}📦 Extension Properties
val String.lastChar: Char
get() = this[length - 1]
var StringBuilder.lastChar: Char
get() = this[length - 1]
set(value) {
this.setCharAt(length - 1, value)
}⚠️ Lưu ý quan trọng
[!WARNING] Extensions are resolved statically, không phải dynamically:
open class Parent class Child : Parent() fun Parent.foo() = "Parent" fun Child.foo() = "Child" fun call(p: Parent) = p.foo() call(Child()) // "Parent" - không phải "Child"!
📱 Trong Android
// View extensions
fun View.show() { visibility = View.VISIBLE }
fun View.hide() { visibility = View.GONE }
fun View.invisible() { visibility = View.INVISIBLE }
// Context extensions
fun Context.toast(message: String) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
}
// Usage
binding.button.show()
toast("Hello!")✅ Checklist
- Tạo extension function
- Tạo extension property
- Hiểu static resolution
- Áp dụng cho utility functions
Tiếp theo: Generics
Last updated on