Constructors in Kotlin are special member functions used to initialize objects of a class. They play a crucial role in object-oriented programming, allowing you to set initial values and perform setup operations when creating new instances.
Kotlin supports two types of constructors:
The primary constructor is part of the class header. It's concise and initializes the class properties directly.
class Person(val name: String, var age: Int) {
// Class body
}
In this example, name
and age
are properties initialized by the primary constructor.
Secondary constructors provide additional ways to initialize a class. They're defined within the class body using the constructor
keyword.
class Person(val name: String) {
var age: Int = 0
constructor(name: String, age: Int) : this(name) {
this.age = age
}
}
Here, we have a primary constructor that initializes name
and a secondary constructor that initializes both name
and age
.
Initialization blocks, denoted by the init
keyword, are executed when the class is instantiated, in the order they appear in the class body.
class Person(val name: String) {
init {
println("Person created with name: $name")
}
}
Constructor parameters can be declared as properties using val
or var
keywords. This automatically creates and initializes the corresponding properties.
class Person(val name: String, var age: Int) {
fun introduce() = "I'm $name and I'm $age years old"
}
To deepen your understanding of Kotlin constructors, explore these related topics:
Mastering constructors is essential for effective Kotlin programming. They provide the foundation for creating flexible and robust object-oriented designs in your applications.