Kotlin Constructors

Introduction

Constructors are special functions used to initialize objects in Kotlin. They are called when an instance of a class is created. Kotlin supports two types of constructors: primary and secondary. This chapter will cover both types of constructors, including their syntax, usage, and examples.

Primary Constructor

The primary constructor is part of the class header and is used to initialize properties. It is concise and can have optional parameters with default values.

Syntax

class ClassName(val property1: Type, var property2: Type) {
    // Class body
}

Example

fun main() {
    // Creating an instance of Person with the primary constructor
    val person = Person("Rahul", 25)
    person.displayInfo() // Calling the displayInfo method
}

class Person(val name: String, var age: Int) {
    // Method to display person information
    fun displayInfo() {
        println("Name: $name, Age: $age")
    }
}

Explanation:

  • class Person(val name: String, var age: Int): Defines a class Person with a primary constructor that initializes the name and age properties.
  • val person = Person("Rahul", 25): Creates an instance of the Person class.
  • person.displayInfo(): Calls the displayInfo method to print the person’s information.

Output:

Name: Rahul, Age: 25

Default Values in Primary Constructor

You can provide default values for parameters in the primary constructor.

Example

fun main() {
    // Creating instances of Person with and without specifying age
    val person1 = Person("Priya")
    val person2 = Person("Amit", 30)
    person1.displayInfo() // Calling the displayInfo method for person1
    person2.displayInfo() // Calling the displayInfo method for person2
}

class Person(val name: String, var age: Int = 25) {
    // Method to display person information
    fun displayInfo() {
        println("Name: $name, Age: $age")
    }
}

Explanation:

  • var age: Int = 25: Provides a default value for the age parameter.
  • val person1 = Person("Priya"): Creates an instance of Person with the default age.
  • val person2 = Person("Amit", 30): Creates an instance of Person with a specified age.

Output:

Name: Priya, Age: 25
Name: Amit, Age: 30

Initializer Blocks

Initializer blocks are used to initialize properties and execute code when an instance of the class is created. They run after the primary constructor.

Example

fun main() {
    // Creating an instance of Person with initializer block
    val person = Person("Anjali", 35)
    person.displayInfo() // Calling the displayInfo method
}

class Person(val name: String, var age: Int) {
    // Initializer block
    init {
        println("Initializer block: Name is $name and age is $age")
    }

    // Method to display person information
    fun displayInfo() {
        println("Name: $name, Age: $age")
    }
}

Explanation:

  • init { ... }: Defines an initializer block that runs after the primary constructor.

Output:

Initializer block: Name is Anjali and age is 35
Name: Anjali, Age: 35

Secondary Constructor

A class can have one or more secondary constructors. They are prefixed with the constructor keyword and are used to provide additional ways to initialize objects.

Syntax

class ClassName {
    constructor(parameter1: Type, parameter2: Type) {
        // Initialization code
    }
}

Example

fun main() {
    // Creating instances of Vehicle with both primary and secondary constructors
    val vehicle1 = Vehicle("Car", "Toyota")
    vehicle1.displayDetails() // Calling the displayDetails method for vehicle1

    val vehicle2 = Vehicle("Bike", "Honda", 2019)
    vehicle2.displayDetails() // Calling the displayDetails method for vehicle2
}

class Vehicle(val type: String, val brand: String) {
    var year: Int = 2020 // Default year

    // Secondary constructor
    constructor(type: String, brand: String, year: Int) : this(type, brand) {
        this.year = year
    }

    // Method to display vehicle details
    fun displayDetails() {
        println("Type: $type, Brand: $brand, Year: $year")
    }
}

Explanation:

  • constructor(type: String, brand: String, year: Int) : this(type, brand) { ... }: Defines a secondary constructor that initializes the year property.
  • val vehicle1 = Vehicle("Car", "Toyota"): Creates an instance of Vehicle using the primary constructor.
  • val vehicle2 = Vehicle("Bike", "Honda", 2019): Creates an instance of Vehicle using the secondary constructor.

Output:

Type: Car, Brand: Toyota, Year: 2020
Type: Bike, Brand: Honda, Year: 2019

Example Program with Constructors

Here is an example program that demonstrates various aspects of constructors in Kotlin:

fun main() {
    // Creating instances of Person with different constructors
    val person1 = Person("Rahul", 25)
    val person2 = Person("Priya")
    person1.displayInfo()
    person2.displayInfo()

    // Creating instances of Vehicle with both primary and secondary constructors
    val vehicle1 = Vehicle("Car", "Toyota")
    vehicle1.displayDetails()

    val vehicle2 = Vehicle("Bike", "Honda", 2019)
    vehicle2.displayDetails()
}

// Basic class with primary constructor
class Person(val name: String, var age: Int = 25) {
    // Initializer block
    init {
        println("Person object is created with name: $name and age: $age")
    }

    // Method to display person information
    fun displayInfo() {
        println("Name: $name, Age: $age")
    }
}

// Class with secondary constructor
class Vehicle(val type: String, val brand: String) {
    var year: Int = 2020 // Default year

    // Secondary constructor
    constructor(type: String, brand: String, year: Int) : this(type, brand) {
        this.year = year
    }

    // Method to display vehicle details
    fun displayDetails() {
        println("Type: $type, Brand: $brand, Year: $year")
    }
}

Output:

Person object is created with name: Rahul and age: 25
Name: Rahul, Age: 25
Person object is created with name: Priya and age: 25
Name: Priya, Age: 25
Type: Car, Brand: Toyota, Year: 2020
Type: Bike, Brand: Honda, Year: 2019

Conclusion

In this chapter, you learned about constructors in Kotlin, including primary and secondary constructors, initializer blocks, and how to use them to create and initialize objects. Understanding these concepts is essential for writing robust and maintainable code in your Kotlin programs.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top