Google News
logo
Kotlin - Interview Questions
How many types of constructors used in a kotlin?
In Kotlin, there are three types of constructors that can be used :

1. Primary Constructor :
   * The primary constructor is defined as part of the class header and is declared after the class name.
   * It can include parameters that serve as properties of the class.
   * The primary constructor cannot contain any code or initialization logic. Initialization code can be placed in `init` blocks.
   Example :
     class MyClass(val name: String, val age: Int) {
         // Initialization code can go in init blocks
         init {
             // ...
         }
     }​


2. Secondary Constructors :
   * Secondary constructors are defined inside the class body.
   * They are prefixed with the `constructor` keyword.
   * Secondary constructors provide additional ways to instantiate objects by providing different sets of parameters or customization options.
   * Secondary constructors must delegate to the primary constructor using the `this` keyword or to another secondary constructor using the `this` keyword followed by the appropriate constructor call.
   Example :
     class MyClass {
         constructor(name: String) {
             // Secondary constructor logic
         }

         constructor(name: String, age: Int) : this(name) {
             // Secondary constructor logic
         }
     }​
3. Init Blocks :
   * Although not technically constructors, `init` blocks are used to initialize properties or execute code during the initialization phase of an object.
   * They are executed when an instance of the class is created, after the primary constructor is called.
   * A class can have multiple `init` blocks, which are executed in the order they appear in the class body.
   Example :
     class MyClass(val name: String, val age: Int) {
         init {
             // Initialization code
         }

         init {
             // Additional initialization code
         }
     }​

It's important to note that the primary constructor is the main constructor of the class and is called when an instance of the class is created. Secondary constructors provide additional options for object creation with different parameter sets, but they must ultimately delegate to the primary constructor. Init blocks are used to execute initialization code during the creation of an object.

These constructor types in Kotlin provide flexibility in defining class properties, customizing object creation, and performing initialization tasks.
Advertisement