Open In App

How to Initialize Constructor in Kotlin?

Last Updated : 30 Jan, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Constructor is a concise way to initialize class properties. or we can say it’s a special member function that is invoked when an object of the class is created primarily to initialize variables or properties. A class needs to have a constructor and if we do not declare a constructor, then the compiler generates a default constructor. It is a special member function that is called when an object is instantiated (created). However, how they work in Kotlin is slightly different. In Kotlin, there are two types of constructors:

  • Primary constructor – concise way to initialize a class
  • Secondary constructor – allows you to put additional initialization logic

In the Java world, we used to initialize fields of the class in the constructor, as shown in this code:

Kotlin




class Student {
  int roll_number;
  String name;
  Student(int roll_number,String name) {
    this.roll_number = roll_number;
    this.name = name;
  }
}


So, if the argument’s name was similar to that of the property (which was usually the case for making the code more readable), we needed to use this keyword. In this recipe, we will see how to implement the same thing in Kotlin (obviously with much less code).

Step by Step Implementation

Let’s look at the mentioned steps to initialize a constructor:

Step 1: Kotlin provides a syntax that can initialize the properties with much less code. Here’s what class initialization looks like in Kotlin:

class Student (var roll_number: Int, var name:String) 

Step 2: You don’t even need to define the body of the class, and the initialization of properties takes place in the primary constructor only (the primary constructor is part of the class header). Obviously, you can either choose var or val, based on whether you need to keep your properties mutable or not. Now, if you try to create an object, you can do so with this:

var student_A=Student (1, "Rashi Karanpuria" )

Step 3: Just to confirm, let’s try to print its properties to see whether we were able to initialize it or not:

printin ("Roll number: $(student_A. roll_number} Name: ${student_A. name}" )

Here’s the output: 

Roll number: 1 Name: Rashi Karanpuria

Step 4: However, if you want, you can also put default values in the constructor:

class Student constructor (var roll_number: Int, var name : String="Sheldon")

Step 5: Then, you can create objects such as this:

var student_sheldon= Student (25) //object with name Sheldon and
age 25
var student_amy=Student (25, "Amy" )  // Object with name Amy and
age 25

Step 6: If the class has a primary constructor, each secondary constructor needs to be delegated to the primary constructor, either directly or indirectly through another secondary constructor(s).

Step 7: We use this keyword to delegate to another constructor of the same class:

class Person (val name: String) {
    constructor (name: String, lastName: String) : this(name) {
    // Do something maybe
    }
}

Step 8: We can also have a situation where we have to initialize other things in the class, not necessarily just the class’s properties. That situation could be opening database connections, for example. In Java, that was done in the constructor itself, but in Kotlin, we have an init block. The initialization code can be put into an init block

class Student (var roll_number: Int, var name: String) { 
init {
        logger. info( "Student initialized")
    }
}

Step 9: Sometimes, we also initialize the properties of a class by dependency injection. If you’ve worked with Dagger2, you must be familiar with objects being directly injected into the constructors of a class. To do so, we append the @Inject annotation before the constructor keyword. Whenever a constructor has an annotation or visibility modifier, we need to have the constructor keyword. An example of the constructor keyword is given below:

class Student #Inject constructor (compositeDisposable:
CompositeDisposable) { . . . }

Step 10: Here, we are injecting an object of the CompositeDisposable type into the constructor and, since we are using an annotation (@Inject) to do so, we need to apply the constructor keyword.

Step 11: When you extend a class, you need to initialize the superclass. This is also very simple in Kotlin. If your class has a primary constructor, the base type must be initialized there, using the parameters of the primary constructor. Here’s an example of the same:

class Student constructor
(var roll_number: Int, var name : String) : Person (name)

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads