Junior — Middle
What types of constructors exist in Kotlin and how are they used in classes?
sobes.tech AI
Answer from AI
In Kotlin, there are two main types of constructors:
- Primary constructor — declared in the class header and initializes the main parameters of the class.
- Secondary constructors — declared inside the class body using the
constructorkeyword and can be used for additional initialization.
Example:
class User(val name: String, var age: Int) { // primary constructor
constructor(name: String) : this(name, 0) { // secondary constructor
println("User created with name $name and default age")
}
}
The primary constructor is usually used for mandatory parameters, while the secondary is for creating objects with different sets of parameters.