Constructors in Kotlin
What is a Constructor?
In Kotlin, a constructor is a special function that is called when an object is created. It is used to initialize the properties of the object. There are two types of constructors in Kotlin: the primary constructor and secondary constructors.
Primary Constructor
The primary constructor is part of the class header and is defined after the class name. It can take parameters and can be used to initialize properties directly.
Example of Primary Constructor
In the example above, the Person class has a primary constructor that takes two parameters: name and age.
To create an instance of the Person class, you can do the following:
Secondary Constructor
Secondary constructors allow you to create additional constructors in a class. They are defined using the constructor keyword and can be used to provide multiple ways to instantiate a class.
Example of Secondary Constructor
In this example, the Person class has a primary constructor that takes only the name, and a secondary constructor that takes both name and age.
You can create an instance using either constructor:
val person2 = Person("Bob", 25) person2.displayInfo()
Name: Alice, Age: 0
Name: Bob, Age: 25
Initializer Blocks
In addition to primary and secondary constructors, Kotlin also allows the use of initializer blocks. These blocks are executed when an instance of the class is created, and they can be used to perform additional initialization.
Example of Initializer Block
The init block is executed every time an instance of Person is created.
Creating an instance will also trigger the initializer block:
Conclusion
Constructors in Kotlin are a powerful feature that allows for flexible object creation and initialization. Understanding both primary and secondary constructors, as well as initializer blocks, is essential for effective Kotlin programming. With this knowledge, you can create classes that are easy to initialize and use, making your code more organized and maintainable.
