Table of contents
1.
Introduction
2.
Kotlin Constructor
3.
Primary Constructor
3.1.
Primary constructor with initialiser block
3.2.
Default Value in Primary Constructor
4.
Secondary Constructor
4.1.
Calling one secondary constructor from another secondary constructor of the same class
4.2.
Calling supper class secondary constructor from the derived class secondary constructor
5.
FAQs
6.
Key Takeaways
Last Updated: Mar 27, 2024

Kotlin Constructor

Author Vasu Bansal
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In this blog, we will discuss constructors in Kotlin. Constructors are very important in any programming language as they help in many initialisation tasks. This blog also introduces you to the different constructors, i.e., primary and secondary constructors. The rules regarding the naming format and other syntax related to constructors are also discussed in later sections.

Kotlin Constructor

A constructor in Kotlin is a piece of code in Kotlin that is analogous to methods. The constructor is named after the class, followed by the parenthesis '()'. At the time of object creation, the function's constructor is used to initialise the variables.

There are two types of constructors present in Kotlin. They are given as follows:

  • Primary Constructor
  • Secondary Constructor

There is only one primary constructor in Kotlin, whereas there can be multiple secondary constructors in Kotlin.

Primary Constructor

The class header includes the primary constructor. The class is initialised using the primary constructor. Parentheses surround the code of the primary constructor with provisions for optional parameters. The use of keyword constructor is optional here. The following program demonstrates the declaration and use of a primary constructor. 

Code:

// Kotlin program to demonstrate primary constructor

// Note the constructor keyword is optional
class Marks_T1_T2 constructor(var num1: Int,var num2:Int)
{    
}

fun main(){    
    println("Sample program to denote Kotlin primary constructor")

    // Test Case 1
    var obj = Marks_T1_T2(5, 10)
    println("The marks in T1 is ${obj.num1}, and the marks in T2 is ${obj.num2}")
}

Output:

Sample program to denote Kotlin primary constructor
The marks in T1 is 5, and the marks in T2 is 10

Primary constructor with initialiser block

The syntax of the primary constructor is very restricted, and it cannot contain any code inside its body. The initialiser block is used to put the initialisation code. It has the keyword init prefixed to it. Let us consider an example program to demonstrate the usage of init block.

Code:

// Kotlin program to demonstrate primary constructor with init block

// Note the constructor keyword is optional
class Marks_T1_T2 constructor(var num1: Int,var num2:Int)
{    
    var marks_t1: Int
    var marks_t2: Int
    init {
        marks_t1 = num1
        marks_t2 = num2
        println("The marks in T1 is $marks_t1 and the marks in T2 is $marks_t2")
    }
}

fun main(){    
    println("Sample program to denote Kotlin primary constructor with init block")

    // Test Case 1
    Marks_T1_T2(5, 10)    
}

Output:

Sample program to denote Kotlin primary constructor with init block
The marks in T1 is 5 and the marks in T2 is 10

Default Value in Primary Constructor

We can provide default values for constructor arguments in the same way we set default values for functions. Let us consider an example program to demonstrate how to set default values in primary constructors.

Code:

// Kotlin program to demonstrate primary constructor with default values

// Note the constructor keyword is optional
class Marks_T1_T2 constructor(var num1: Int = -1,var num2:Int = -1)
{    
    var marks_t1: Int
    var marks_t2: Int
    init {
        marks_t1 = num1
        marks_t2 = num2
        println("The marks in T1 is $marks_t1 and the marks in T2 is $marks_t2")
    }
}

fun main(){    
    println("Sample program to denote Kotlin primary constructor with default values")

    Marks_T1_T2()    
}

Output:

Sample program to denote Kotlin primary constructor with default values
The marks in T1 is -1 and the marks in T2 is -1

Secondary Constructor

It is possible to have multiple secondary constructors in a class in Kotlin. The keyword constructor is used to create them. In Kotlin, secondary constructors are usually not common. The most common use of a secondary constructor is when you need to extend a class with multiple constructors that initialise the class in different ways. Let us consider an example program to demonstrate using secondary constructors in Kotlin.

Code:

// Kotlin program to demonstrate secondary constructor

class Ninja
{    
    constructor(arg1: String){
        println("Constructor Type 1: ${arg1}")
    }

    constructor(arg1: String, arg2: String){
        println("Constructor Type 2: ${arg1} --> ${arg2}")
    }

    constructor(arg1: String,arg2: String, arg3: String){
        println("Constructor Type 3: ${arg1} --> ${arg2} --> ${arg3}")
    }
}

fun main(){    
    Ninja("Code and Code")
    Ninja("Code and Code", "Become a Ninja")
    Ninja("Code and Code", "Become a Ninja", "By Joining Coding Ninjas")
}

Output:

Constructor Type 1: Code and Code
Constructor Type 2: Code and Code --> Become a Ninja
Constructor Type 3: Code and Code --> Become a Ninja --> By Joining Coding Ninjas

Calling one secondary constructor from another secondary constructor of the same class

Kotlin provides the flexibility to call one secondary constructor from another with the help of this keyword. Let us consider an example program to demonstrate this concept.

Code:

// Kotlin program to demonstrate calling one secondary constructor from another secondary constructor

class Ninja
{    
    constructor(arg1: String):this(arg1,"from constructor 1"){
        println("Constructor Type 1: ${arg1}")
    }

    constructor(arg1: String, arg2: String): this(arg1,arg2,"from constructor 2"){
        println("Constructor Type 2: ${arg1} --> ${arg2}")
    }

    constructor(arg1: String,arg2: String, arg3: String){
        println("Constructor Type 3: ${arg1} --> ${arg2} --> ${arg3}")
    }
}

fun main(){      
    Ninja("Code and Code")
}

Output:

Constructor Type 3: Code and Code --> from constructor 1 --> from constructor 2
Constructor Type 2: Code and Code --> from constructor 1
Constructor Type 1: Code and Code

Calling supper class secondary constructor from the derived class secondary constructor

Kotlin allows the secondary constructor of the derived class to invoke the secondary constructor of the base class. It is a concept of inheritance and is achieved using the super keyword. Let us consider an example program to demonstrate the use of this concept.

Code:

// Kotlin program to demonstrate secondary constructor and inheritance concepts

open class Student {
    constructor (ninja_id: Int, student_name: String) {
        println("Base Class Constructor --> Ninja ID: ${ninja_id} and Student Name: ${student_name}")
    }
}
class Ninja : Student {
    constructor (ninja_id : Int):super(ninja_id,"Code Studio"){
        println("Child Class Constructor --> Ninja ID: ${ninja_id}")
    }
}

fun main(){    
    Ninja(1)
}

Output:

Base Class Constructor --> Ninja ID: 1 and Student Name: Code Studio
Child Class Constructor --> Ninja ID: 1

To read more about inheritance in Kotlin, refer to the blog Kotlin inheritance on the Coding Ninjas Website.

You can also check out Singleton Design Pattern C# here.

Must Read Elvis Operator Kotlin

FAQs

  1. What is suspended function in Kotlin?
    A function that may be started, halted, then resumed is known as a suspend function.
     
  2. What is singleton in Kotlin?
    Singleton is a software design pattern that limits the number of instances of a class to only one.
     
  3. What happens when all primary constructors are parametrized and have some default values?
    The compiler will create a new parameterless constructor that uses the default values defined in the given constructors.

Key Takeaways

Cheers if you reached here!! This blog aimed to discuss the concept of constructors in Kotlin. Go ahead and read the blog Kotlin Classes and Objects to learn more about the use of classes and objects in Kotlin.  

Check out this article - Balanced Parentheses

Yet there is never an end to the learning process, so check out our Android Development Course on the Coding Ninjas Website to learn everything you need to know about Android development and how to design the applications of future

Happy learning !!

Live masterclass