Kotlin Constructor
Overview
A constructor in Kotlin plays a pivotal role in object initialization, offering flexibility and customization. This article delves into Kotlin's primary and secondary constructors, shedding light on their features, use cases, and benefits. By understanding these versatile constructors, developers can enhance code organization, reuse logic efficiently, and create adaptable classes.
Constructor in Kotlin
A constructor in Kotlin is an integral part of object-oriented programming and play a significant role in creating and initializing instances of classes. A constructor in Kotlin allows developers to set up the initial state of an object when it is created and provide a mechanism for passing required and optional parameters during object instantiation.
Types of Constructors in Kotlin
A constructor in Kotlin could be of the following two types:
- Primary constructor
- Secondary constructor
In Kotlin, a class is allowed to have a only one primary constructor. Additionally, it can have multiple secondary constructors. The primary constructor is responsible for initializing the class, whereas the secondary constructors serve the purpose of both initializing the class and incorporating supplementary logic.
Let's discuss primary and secondary constructor in Kotlin in detail.
Primary Constructor
The primary constructor in Kotlin is the main constructor defined directly within the class header. It is where you declare the properties that will be initialized when an object of the class is created. It is defined in the header of the class with a constructor keyword. For primary constructor in Kotlin, the parameters are optional. Consider the following code snippet.
Code:
You can omit the constructor keyword if no annotations or access modifiers are specified.
Code:
1. Kotlin program of primary constructor
Code:
Output:
Explanation:
In the main() function, an instance of the Person class is created with the arguments "John" and "Doe". The greet() function is called on this object, which prints the output.
2. Primary Constructor with Initializer Block
The primary constructor in Kotlin is not designed to hold any code. The initialization code can be segregated into a distinct initializer block marked with the init keyword.
The init block functions as an initialization block in which member variables are set up. This block is executed every time an instance of the associated class is generated.
Multiple init blocks are permissible, and they are invoked in the sequence they are positioned within the class.
Code:
Output:
Explanation:
In this example, the Person class has a primary constructor with two parameters: firstName and lastName. There are three initializer blocks following the parameter list of constructor in Kotlin. The initializer blocks execute in the order they appear, after the primary constructor's parameters have been processed. This approach can be useful if you need to perform different initialization tasks for various properties or if you want to ensure a specific sequence of initialization operations.
Note: The init block has access to the constructor parameters.
Consider the following code snippet.
Code:
Output:
3. Default value in primary constructor
You can provide default values for parameters in the primary constructor in Kotlin. This allows you to create objects without specifying all parameters explicitly.
Code:
Explanation:
In this example, the Person class has a primary constructor with two parameters: firstName and lastName. Both parameters have default values assigned ("John" and "Doe" respectively).
Now, you can create Person objects in different ways:
Provide Both First Name and Last Name
Code:
Provide Only First Name
Code:
Use Default Values for Both Parameters:
Code:
By assigning default values to constructor parameters, you provide a convenient way to create objects without having to specify all values explicitly. It eliminates the need to provide values for parameters that have reasonable defaults.
Secondary Constructor
A Secondary constructor in Kotlin is defined within a class that allows you to provide different ways to instantiate objects. Unlike the primary constructor, secondary constructors do not initialize properties directly; they delegate to the primary constructor. The secondary constructor in Kotlin is defined using the constructor keyword.
Of all the available secondary constructors, which one is called is decided by the compiler based on the arguments received.
1. Kotlin program of implementing secondary constructor
Code:
Output:
Explanation:
It takes two parameters: number1 and number2, which represent the numbers to be multiplied. Inside the secondary constructor, we calculate the multiplication result and assign it to the result property.
2. Kotlin program of two secondary constructors in a class
You can define multiple secondary constructors in Kotlin to provide different ways to create objects. Here's an example of a Kotlin program that demonstrates a class with two secondary constructors:
Code:
Output:
Explanation:
In this program, we define a Rectangle class that represents rectangles and squares with different constructors:
- The first secondary constructor takes a sideLength parameter. Inside the constructor, both width and height are set to the value of sideLength. This constructor is used to create squares.
- The second secondary constructor takes separate width and height parameters. It sets the width and height properties accordingly. This constructor is used to create general rectangles.
- In the main() function, we create two Rectangle objects: square and rectangle. The square object is created using the first secondary constructor, and the rectangle object is created using the second secondary constructor.
3. Kotlin program of three secondary constructors in a class
Code:
Output:
Explanation:
In this program, we define a Calculator class with three secondary constructors:
- The first secondary constructor in Kotlin takes a single number parameter and sets the result to that number. This constructor is used to create a calculator with an initial value.
- The second secondary constructor in Kotlin takes two parameters, number1 and number2, and sets the result to their sum. This constructor is used to perform addition.
- The third secondary constructor in Kotlin takes three parameters: number1, number2, and operation. It calculates the result based on the specified operation ("add", "subtract", or "multiply"). If the operation is not recognized, it throws an exception.
- In the main() function, we create three Calculator objects using the different secondary constructors.
4. Calling one secondary constructor from another
Code:
Output:
Explanation:
- The Person class has two secondary constructors:
- The first secondary constructor in Kotlin takes only a name parameter. It calls the second secondary constructor using this(name, ""). This constructor is used when only the first name is provided.
- The second secondary constructor in Kotlin takes both firstName and lastName parameters. It initializes the properties directly.
- In the main function, we create two Person objects: person1 and person2.
- person1 is created using the first secondary constructor with just a name.
- person2 is created using the second secondary constructor with both first and last names.
- The getFullName() function retrieves the full name of each person, which is then printed in the main() function.
5. Calling parent class secondary constructor from child class secondary constructor
We have the ability to invoke the secondary constructor in Kotlin of the parent class from the child class using the super keyword. The program below illustrates the procedure of making such a call.
Consider a class Person with a primary constructor in Kotlin and two secondary constructors in Kotlin:
Code:
Output:
Explanation:
- We define an open class named Parent. It has a secondary constructor that takes an Int parameter. Inside the constructor, we print a message indicating that the parent secondary constructor has been called with the provided parameter.
- We then define a class named Child that extends the Parent class. In the Child class, we define a secondary constructor that also takes an Int parameter. To call the secondary constructor of the parent class, we use the super keyword followed by the parameter we want to pass.
- Inside the Child constructor, we print a message to indicate that the child secondary constructor has been called.
- In the main() function, we create an instance of the Child class and pass the parameter 42 to the constructor. This triggers the constructor chain, first calling the parent's secondary constructor and then the child's secondary constructor.
Conclusion
Here are the key takeaways from the article:
- A constructor in Kotlin provides versatile means of creating objects. They allow you to define various ways to pass arguments, accommodating different use cases and scenarios.
- A secondary constructor in Kotlin contribute sto efficient code reuse. By delegating initialization logic to other constructors, you avoid duplicating code and promote a cleaner codebase.
- A constructor in Kotlin serves as central points for object initialization. Placing setup code within constructors ensures that properties are consistently and correctly initialized, reducing the likelihood of errors.
- Default parameter values enhance code simplicity. You can create objects without specifying all parameters, making code cleaner and easier to read, especially for classes with many properties.
- Initializer blocks enable precise control over initialization order. Tasks within these blocks execute sequentially, allowing you to enforce a specific sequence of operations during object creation.