Constructor trong Kotlin - Primary và Secondary
1. Giới thiệu
Kotlin có hai loại constructor: Primary (chính) và Secondary (phụ).
2. Primary Constructor
class Person(val name: String, var age: Int)
// Với từ khóa constructor (optional)
class User constructor(val email: String)
fun main() {
val person = Person("Alice", 25)
println(person.name) // Alice
}3. Primary với init block
class Person(val name: String) {
val nameLength: Int
init {
println("Đang tạo person: $name")
nameLength = name.length
}
init {
println("Có thể có nhiều init blocks")
}
}4. Default Values
class Config(
val host: String = "localhost",
val port: Int = 8080,
val secure: Boolean = false
)
fun main() {
val default = Config()
val custom = Config(port = 3000)
val full = Config("api.example.com", 443, true)
}5. Secondary Constructor
class Person {
var name: String
var age: Int
constructor(name: String) {
this.name = name
this.age = 0
}
constructor(name: String, age: Int) {
this.name = name
this.age = age
}
}6. Secondary gọi Primary
class Person(val name: String, val age: Int) {
var email: String = ""
constructor(name: String, age: Int, email: String) : this(name, age) {
this.email = email
}
}7. Private Constructor
class Singleton private constructor() {
companion object {
private val instance = Singleton()
fun getInstance() = instance
}
}
fun main() {
// val s = Singleton() // Error! Private constructor
val s = Singleton.getInstance()
}8. Constructor với validation
class Age(value: Int) {
val value: Int
init {
require(value >= 0) { "Age must be non-negative" }
require(value <= 150) { "Age seems unrealistic" }
this.value = value
}
}
fun main() {
val age = Age(25) // OK
// val bad = Age(-5) // IllegalArgumentException
}9. Kế thừa Constructor
open class Animal(val name: String)
class Dog(name: String, val breed: String) : Animal(name)
class Cat : Animal {
val color: String
constructor(name: String, color: String) : super(name) {
this.color = color
}
}10. So sánh với Java
// Kotlin - ngắn gọn
class Person(val name: String, var age: Int)
// Java - dài dòng
/*
public class Person {
private final String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() { return name; }
public int getAge() { return age; }
public void setAge(int age) { this.age = age; }
}
*/📝 Tóm tắt
- Primary constructor trong class header
initblock cho initialization logic- Secondary constructor với
constructorkeyword - Secondary phải gọi primary với
this() - Default values giảm số constructor cần thiết
private constructorcho singleton pattern
Last updated on