Kotlin Constructors

Having read about the kotlin classes and objects, let’s have a look at initialization of class objects. This can be done using constructors. So in simple words:

“A constructor is a special member function which is called when the object is instantiated or created.”

Before we move ahead and discuss about various types of constructor and their usage, let’s have a look at characteristics of constructor:

  • Constructor is block of code similar to method.
  • It has the same name as that of the class.
  • Constructor has no return type, not even void.

Kotlin Constructors

Constructor in kotlin are a bit different from the basic working of constructor.

Kotlin offers two types of constructors:

  1. Primary Constructor
  2. Secondary Constructor

Primary Constructor

It is the part of class header and is used to initialize class. Primary Constructor is surrounded by parenthesis, though the parameters are optional.

As per standard definition procedure, the Primary Constructor does not supports any code. It’s advisable not to confuse this constructor to Java Constructor as in Java the constructor is used to initialize the member variables, whereas, Kotlin uses the primary constructor to initialize class.

A typical primary constructor goes like the one shown below:

class HelloWorldClass(< Optional Parameters >) {  
   // class body  
}

Below is an example of the basic class with a primary constructor.

fun main(args: Array<String>) {  
    val stu = Student("Kotlin Blog", 1)  
    println("Name = ${stu.name}") 
    println("Id = ${stu.id}") 
}

class Student(val name: String, var id: Int) {  
}

Output:

Name = Kotlin Blog
Id = 1

An interesting fact to note here is that primary constructor is not having any body. To initialize the value to the variables or set some default value we need to use “Initializer Block”. We can create an initializer block by using the init keyword and these are called at the time of instance initialization.

Below is an example of primary constructor with an initialization block:

class Student(stuName: String, roll: Int) {
	val name: String  
	var stuRoll: Int  

	init{
		name = stuName.capitalize()
		stuRoll = roll

		println("Name = ${name}")
		println("Roll = ${stuRoll}")
	}
}  

fun main(args: Array<String>){  
	val stu = Student ("Ram", 1)  
}

Output:

Name = Ram
Roll = 1

Here we have used the init block to initialize the value of the two variables which are declared in the primary constructor and used in the class. Kindly note that init blocks are executed in the same order in which these appear in the body of the class.

In case when we want to have some default value to be assigned, we can use Primary Constructor with default values like shown in the example below:

fun main(args: Array<String>) {
    println("Student1 is instantiated")
    val stu = Student("joe", 25)
    println("Student2 is instantiated")
    val stu1 = Student("Jack")
    println("Student3 is instantiated")
    val stu2 = Student()
}

class Student(stuName: String = "Name", stuRoll: Int = 1) {
    val stuName = stuName.capitalize()
    var stuRoll = stuRoll
    // initializer block
    init {
        println("Student Name = $stuName")
        println("Student Roll = $stuRoll\n")
    }
}

Output:

Student1 is instantiated
Student Name = joe
Student Roll = 25

Student2 is instantiated
Student Name = Jack
Student Roll = 1

Student3 is instantiated
Student Name = Name
Student Roll = 1

Any class in Kotlin can have at most 1 primary constructor. In case if we want to provide custom constructors we use Secondary Constructor, let’s have a look at secondary constructor in detail.

Secondary Constructor

In case when we want our constructor to have some business logic, we can use secondary constructor. We can define secondary constructor using the constructor keyword. Let’s see a basic example to understand the basic use of secondary constructor:

class Helloworld{
	constructor(message: String,name: String){
		println("${message} ${name} !,")
	}  
}

fun main(args: Array<String>){
	val hwMessage = Helloworld ("Hello World ", "Kotlin blog")  
}

Output:

Hello World Kotlin blog !,

The best part of using secondary constructor is that it can be clubbed to be used with Primary constructor as well. In case when the secondary constructor has to authorize the primary constructor and same can be done using this() keyword.

class User(password: String){
    constructor(userName: String, regId: Int, password: String): this(password){  
        println("Name = ${userName}")  
        println("Id = ${regId}")  
        println("Password = ${password}")  
    }  
}  

fun main(args: Array<String>){  
val user1 = User ("administrator", 101, "password1")  
}

Output:

Name = administrator
Id = 101
Password = password1

There’s another use case, when the user wants to call a secondary constructor from another secondary constructor. The same can be done using this() keyword as shown in the example below:

class User{  
    constructor(userName: String, regId: Int): this(userName,regId, "password"){  
        println(" Second Constructor being called. ")  
        println("userName = ${userName}")  
        println("Reg Id = ${regId}")  
    }  
  
    constructor(userName: String, regId: Int,pass: String){  
        println("Secondary Constructor to be called first. ")  
        println("userName = ${userName}")  
        println("Reg Id = ${regId}")  
        println("Password = ${pass}")  
    }  
}  

fun main(args: Array<String>){  
    val user2 = User ("UserName2", 2)  
}

Output:

Secondary Constructor to be called first.
userName = UserName2
Reg Id = 2
Password = password
Second Constructor being called.
userName = UserName2
Reg Id = 2

The most important thing to note is here that it is mandatory for the secondary constructor must initialize the base class or delegate to another constructor if the class is not having any other primary constructor.

With this we are done with kotlin constructors, constructors can be put to use with class that inherit property from other classes. Let’s have a look at the further concepts of constructors which can come to use with Inheritance till then Happy Coding!

Leave a Comment

Subscribe For Latest Updates

Signup for our newsletter and get notified when we publish new articles for free!