Companion Object trong Kotlin
🎯 Mục tiêu: Hiểu Companion Object - thay thế cho static members trong Java.
💡 Khái niệm
Kotlin không có static keyword. Thay vào đó, sử dụng companion object.
class User(val name: String) {
companion object {
fun fromJson(json: String): User {
return User(json) // Simplified
}
}
}
val user = User.fromJson("""{"name":"Alice"}""")📝 Cú pháp
class MyClass {
companion object Factory { // Có thể có tên
const val CONSTANT = 100
fun create(): MyClass = MyClass()
}
}
// Tên mặc định là "Companion"
class Other {
companion object {
fun method() { }
}
}
Other.method()
Other.Companion.method() // Cũng OK🎯 Factory Pattern
class User private constructor(val name: String, val role: String) {
companion object {
fun createAdmin(name: String) = User(name, "admin")
fun createGuest() = User("Guest", "guest")
fun fromDatabase(id: Int): User? = null // Load from DB
}
}
val admin = User.createAdmin("Alice")
val guest = User.createGuest()✅ Checklist
- Sử dụng companion object thay static
- Tạo factory methods
- Định nghĩa constants với
const val
Last updated on