Kotlin constructor

04 Jul, 2022
A constructor is 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.
Kotlin has two types of constructors – 
Primary ConstructorSecondary Constructor  
Primary Constructor
Secondary Constructor  
A class in Kotlin can have at most one primary constructor, and one or more secondary constructors. The primary constructor initializes the class, while the secondary constructor is used to initialize the class and introduce some extra logic.
The primary constructor is initialized in the class header, goes after the class name, using the constructor keyword. The parameters are optional in the primary constructor. 
class Add constructor(val a: Int, val b: Int) {
     // code
}
The constructor keyword can be omitted if there is no annotations or access modifiers specified.  
class Add(val a: Int, val b: Int) {
     // code
}
Kotlin program of primary constructor – 
Java
//main functionfun main(args: Array<String>){    val add = Add(5, 6)    println("The Sum of numbers 5 and 6 is: ${add.c}")}//primary constructorclass Add constructor(a: Int,b:Int){    var c = a+b;}
Output: 
The Sum of two numbers is: 11
Explanation: When we create the object add for the class then the values 5 and 6 passes to the constructor. The constructor parameters a and b initialize with the parameters 5 and 6 respectively. The local variable c contains the sum of variables. In the main, we access the property of constructor using ${add.c}. 
The primary constructor cannot contain any code, the initialization code can be placed in a separate initializer block prefixed with the init keyword.Kotlin program of primary constructor with initializer block – 
what is init block? 
It acts as an initialiser block where member variables are initialised. This block gets executed whenever an instance of this class is created.
There can be multiple init blocks and they are called in the order they are written inside the class.
Note : init blocks gets called before the constructor of this class is called.
Kotlin
fun main(args: Array<String>) {    val person = Person("Mahmood")}class Person {       constructor(name : String){        println("This is primary constructor")    }          init{        println("This is first init block")    }         init{        println("This is second init block")    }         init{        println("This is third init block")    }      }
Output: 
This is first init block
This is second init block
This is third init block
This is primary constructor
Explanation: When the object person is created for the class Person, the value “Mahmood” passed to the parameters name of the constructor. Two properties are declared in the class id and name.Initializer block is executed at the time of object creation, and not only initialize the properties but also prints to the standard output.
Similar to functions default values in functions, we can initialize the constructor parameters with some default values.Kotlin program of default values in primary constructor – 
Java
fun main(args: Array<String>) {    val emp = employee(18018, "Sagnik")    // default value for emp_name will be used here    val emp2 = employee(11011)    // default values for both parameters because no arguments passed    val emp3 = employee() }class employee(emp_id : Int = 100 , emp_name: String = "abc") {    val id: Int    var name: String     // initializer block    init {        id = emp_id        name = emp_name         print("Employee id is: $id, ")        println("Employee name: $name")        println()    }}
Output: 
Employee id is: 18018, Employee name: Sagnik

Employee id is: 11011, Employee name: abc

Employee id is: 100, Employee name: abc
Explanation: Here, we have initialized the constructor parameters with some default values emp_id = 100 and emp_name = “abc”. When the object emp is created we passed the values for both the parameters so it prints those values. But, at the time of object emp2 creation, we have not passed the emp_name so initializer block uses the default values and print to the standard output. 
As mentioned above, Kotlin may have one or more secondary constructors. Secondary constructors allow initialization of variables and allow to provide some logic to the class as well. They are prefixed with the constructor keyword.
Kotlin program of implementing secondary constructor-  
Java
//main functionfun main(args: Array<String>){    Add(5, 6)}//class with one secondary constructorclass Add{    constructor(a: Int, b:Int)    {        var c = a + b        println("The sum of numbers 5 and 6 is: ${c}")    }}
Output: 
The sum of numbers 5 and 6 is: 11
Which secondary constructor will be called is decided by the compiler based on the arguments received. In the above program, we does not specify to invoke which constructor and compiler decides by itself.
Kotlin program of two secondary constructors in a class-  
Java
fun main(args: Array<String>) {    employee(18018, "Sagnik")    employee(11011,"Praveen",600000.5)}class employee {       constructor (emp_id : Int, emp_name: String ) {          var id: Int = emp_id          var name: String = emp_name          print("Employee id is: $id, ")          println("Employee name: $name")          println()      }        constructor (emp_id : Int, emp_name: String ,emp_salary : Double) {           var id: Int = emp_id           var name: String = emp_name           var salary : Double = emp_salary           print("Employee id is: $id, ")           print("Employee name: $name, ")           println("Employee name: $salary")       }}
Output: 
Employee id is: 18018, Employee name: Sagnik

Employee id is: 11011, Employee name: Praveen, Employee name: 600000.5
Kotlin program of three secondary constructor in a class –  
Java
//main functionfun main(args: Array<String>){    Add(5, 6)    Add(5, 6, 7)    Add(5, 6, 7, 8)}//class with three secondary constructorsclass Add{    constructor(a: Int, b: Int)    {        var c = a + b        println("Sum of 5, 6 = ${c}")    }    constructor(a: Int, b: Int, c: Int)    {        var d = a + b + c        println("Sum of 5, 6, 7 = ${d}")    }    constructor(a: Int, b: Int, c: Int, d: Int)    {        var e = a + b + c + d        println("Sum of 5, 6, 7, 8 = ${e}")    }}
Output: 
Sum of 5, 6 = 11
Sum of 5, 6, 7 = 18
Sum of 5, 6, 7, 8 = 26 
A secondary constructor may call another secondary constructor of the same class using this() function. In the below program, we have called the another constructor using this(a,b,7) because invoking of that constructor require three parameters.
Kotlin program of calling one constructor from another-  
Java
//main functionfun main(args: Array<String>){    Add(5,6)}class Add {    // calling another secondary using this    constructor(a: Int,b:Int) : this(a,b,7) {        var sumOfTwo = a + b        println("The sum of two numbers 5 and 6 is: $sumOfTwo")    }    // this executes first    constructor(a: Int, b: Int,c: Int) {        var sumOfThree = a + b + c        println("The sum of three numbers 5,6 and 7 is: $sumOfThree")    }}
Output:  
The sum of three numbers 5,6 and 7 is: 18
The sum of two numbers 5 and 6 is: 11 
We can call the secondary constructor of parent class from the child class using the super keyword. In the below program, we have shown the process of calling. 
Java
fun main(args: Array<String>) {    Child(18018, "Sagnik")}open class Parent {    constructor (emp_id: Int, emp_name: String, emp_salary: Double) {        var id: Int = emp_id        var name: String = emp_name        var salary : Double = emp_salary        println("Employee id is: $id")        println("Employee name: $name")        println("Employee salary: $salary")        println()    }}class Child : Parent {    constructor (emp_id : Int, emp_name: String):super(emp_id,emp_name,500000.55){        var id: Int = emp_id        var name: String = emp_name        println("Employee id is: $id")        println("Employee name: $name")    }}
Output: 
Employee id is: 18018
Employee name: Sagnik
Employee salary: 500000.55

Employee id is: 18018
Employee name: Sagnik
Akanksha_Rai
simmytarika5
rajeev0719singh
gaudentas199
Kotlin OOPs
Picked
Kotlin
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Add Views Dynamically and Store Data in Arraylist in Android?
Android RecyclerView in Kotlin
Broadcast Receiver in Android With Example
How to Communicate Between Fragments in Android?
Content Providers in Android with Example
Retrofit with Kotlin Coroutine in Android
How to Add and Customize Back Button of Action Bar in Android?
Kotlin Higher-Order Functions
Suspend Function In Kotlin Coroutines
How to Change the Color of Status Bar in an Android App?