Kotlin, as a modern programming language, introduced a more intuitive and concise way of handling constructors compared to its counterpart Java. We have a primary constructor and one or more secondary constructors in the Kotlin class.
Now, this article aims to help you understand Kotlin Constructors in detail. We will learn about the class header, primary constructor, and secondary constructor(s) in Kotlin, along with relevant Kotlin constructor examples.
In Kotlin, constructors are special member functions that are used to initialize properties of the class or object. If no constructor is explicitly declared, Kotlin automatically generates a 'default constructor' to initialize the class. The Kotlin constructor is called automatically when we create an object of a class.
Constructors in Kotlin have their unique utility. Whenever you create a class instance, the constructor initializes the member properties. Let's say we have a Person class, the class person constructor will initialize properties like name, age, etc., at the time of object creation.
In Kotlin, the primary constructor is a part of the class header. It is declared immediately after the class name. Constructor parameters in the primary constructor can include types and default values for more flexible object initialization, allowing for a more streamlined and efficient way to create objects. Let’s take a look at the class person constructor example. Kotlin class constructor’s syntax is as follows:
1class Employee constructor(firstName: String, age: Int) {}
In the Primary constructor, the constructor keyword can be removed if there are no access modifiers or annotations. For instance,
1class Employee(firstName: String, age: Int) {}
In the above example, the class Employee has a constructor with two parameters firstName and age. Parameters in the primary constructor can be assigned 'default values' to simplify object creation, enhancing the flexibility and usability of Kotlin classes.
Here, in the class header, we define the primary constructor right after the class name, indicating the parameters required for object creation.
1class Employee(var name: String, var age: Int) {}
In the Employee class example above, we used the var keyword, indicating that the Employee's name and age can be modified.
Let’s demonstrate this with a Kotlin constructor example:
1class Employee(var name: String, var age: Int) { 2 var count: Int = 0 3 4 init { 5 count += 1 6 println("Employee instance created with name = $name, age = $age, count = $count") 7 } 8} 9 10fun main() { 11 val employee = Employee("Ben", 25) 12}
In the Kotlin class constructor above, we have used an initializer block along with the keyword init. The init block will be called when the class instance is created. The 'init' keyword plays a crucial role in executing initialization code within the context of the primary constructor, allowing for the initialization of member variables and ensuring that the initialization logic is properly managed during the creation of an instance.
This example creates a Kotlin class named Person. In the class body, we declare a variable count, which we increment every time a new instance of the class is created.
In addition to the primary constructor, Kotlin also allows for secondary constructors for additional initializations or to accommodate different parameters. The keyword constructor is used to declare secondary constructors in Kotlin. Unlike secondary constructors, a default constructor is provided by Kotlin when no explicit constructor is defined, serving to initialize variables or properties when an object of the class is created. This contrasts with secondary constructors that are explicitly declared to handle additional initialization requirements or different sets of parameters.
1class Car { 2 constructor(make: String, model: String) { 3 // code to be executed 4 } 5}
In the Car class above, the secondary constructor accepts two properties: make and model.
The syntax of a secondary constructor is slightly different from that of a primary constructor. In the secondary constructor, the constructor keyword is mandatory. The secondary constructor is defined inside the class body.
1class Person(val name: String) { 2 var age: Int = 0 3 constructor(name: String, age: Int) : this(name) { 4 this.age = age 5 } 6}
In the above Kotlin class, the Person class has a primary constructor with a name parameter and a secondary constructor with name and age parameters. The secondary constructor calls the primary constructor and initializes the age property.
Secondary constructors can be beneficial when you need to initialize your class in different ways. For instance, you may have a user where sometimes you have the age info, and sometimes you don't. For such cases, secondary constructors are profoundly significant to set up your Kotlin class in a convenient way.
To further comprehend the concept, let’s write a Kotlin secondary constructor example:
1class Employee(val name: String) { 2 var age: Int? = null 3 4 constructor(name: String, age: Int) : this(name) { 5 this.age = age 6 } 7 8 fun printDetails() { 9 if (age != null) { 10 println("Employee $name is of $age years old.") 11 } else { 12 println("Employee name is $name.") 13 } 14 } 15} 16 17fun main(args: Array<String>) { 18 val employee1 = Employee("John",30) 19 val employee2 = Employee("Mary") 20 21 employee1.printDetails() 22 employee2.printDetails() 23 24 // Demonstrating how 'main args array string' can be used to pass arguments to constructors when creating objects. 25}
In the above example, an Employee class is defined with both a primary and secondary constructor. When creating class instances in the fun main args array, different constructors are being called. The printDetails function determines how to print based on whether the age is initialized.
Kotlin provides the flexibility to use both primary and secondary constructors concurrently in the same class. Here, secondary constructors need to delegate to the primary constructor using the 'this' keyword. This enables different ways to initialize objects of the same class based on the requirements.
1class Child(val name: String) { 2 var age: Int = 0 3 var id: Int = 0 4 5 constructor(name: String, age: Int) : this(name) { 6 this.age = age 7 } 8 constructor(name: String, id: Int, age: Int) : this(name, age) { 9 this.id = id 10 } 11}
In the above code example of the Child class, three constructors are defined. The constructors initialize name, age, and id, offering flexibility in creating Children class instances with different parameters specified.
Understanding Kotlin Constructors and their different types and uses is fundamental to effective Kotlin programming. The primary and secondary constructors in Kotlin offer simplicity and elegance, allowing for more coherent and readable code. Also, Kotlin's constructors reflect the language's overall design philosophy - being concise, expressive, and interoperable.
This guide has helped clarify the syntax and usage of these constructors along with examples. With this knowledge, you can now leverage constructors effectively in your Kotlin applications. Remember, practice makes you better at coding, so keep writing and refining Kotlin code.
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.