Constructors in Kotlin: How Do They Differ from Java?

In Java, we can easily declare one or more constructors using the class name with different parameters, and there is no hierarchy of constructors. For example:

class Student {

    Student() { }

    Student(int name, int class) { }

    Student(int name, int class, int marks) { }

}

However, Kotlin simplifies the process of creating and using constructors compared to Java. Constructors in Kotlin can be categorized into two main types: Primary constructors and Secondary constructors.

Primary Constructors:

· Defined in the class header after the class name.

· Initialize properties directly, reducing boilerplate code.

· May include init blocks for additional initialization logic.

init -> In Kotlin, 'init' refers to an initialization block. It is executed only once when an object of a class is created, and it runs after the execution of the primary constructor. The 'init' block allows you to perform custom initialization logic for the class.

· Ensures consistent property initialization order.

class Student (age:Int){
     inti  {
           // Initialization logic here
      }
}

class Student constructor(age:Int){
      inti  {
           // Initialization logic here
      }
}
// both declarations are the same

Secondary Constructors:

· Defined using the constructor keyword.

· Can be used to create multiple constructors with different parameter sets.

· There is a hierarchy in the declaration of constructors in Kotlin

Primary constructor -> inti block -> secondary constructor

class Student(namePrimary: String) {
    var stuName: String
    var stuAge: Int = 0

     init {
       this.stuName = namePrimary
      }

    constructor(name: String, age: Int) : this(name) {
         this.stuName = name
         this.stuAge = age
      }
}

As we can see in the above code, whenever we call the secondary constructor, the Primary constructor is called first, then the init block will execute, and after that, the secondary constructor is called.