Kotlin constructor

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 –

  1. Primary Constructor
  2. 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.

Primary Constructor –

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 –

filter_none

edit
close

play_arrow

link
brightness_4
code

//main function
fun main(args: Array<String>)
{
    val add = Add(5, 6)
    println("The Sum of numbers 5 and 6 is: ${add.c}")
}
//primary constructor
class Add constructor(a: Int,b:Int)
{
    var c = a+b;
}

chevron_right


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 contructor using ${add.c}.

Primary Constructor with Initializer Block –

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 –

filter_none

edit
close

play_arrow

link
brightness_4
code

fun main(args: Array<String>) {
    val emp = employee(18018, "Sagnik")
}
class employee(emp_id : Int , emp_name: String) {
    val id: Int
    var name: String
  
    // initializer block
    init {
        id = emp_id
        name = emp_name
  
        println("Employee id is: $id")
        println("Employee name: $name")
    }
}

chevron_right


Output:

Employee id is: 18018
Employee name: Sagnik

Explanation:
When the object emp is created for the class employee, the values 18018 and “Sagnik” passed to the parameters emp_id and emp_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.

Default value in primary constructor –

Similar to functions default values in functions, we can initialize the constructor parameters with some default values.

Koltin program of default values in primary constructor –

filter_none

edit
close

play_arrow

link
brightness_4
code

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()
    }
}

chevron_right


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.

Secondary Constructor –

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-

filter_none

edit
close

play_arrow

link
brightness_4
code

//main function
fun main(args: Array<String>)
{
    Add(5, 6)
}
//class with one secondary constructor
class Add
{
    constructor(a: Int, b:Int)
    {
        var c = a + b
        println("The sum of numbers 5 and 6 is: ${c}")
    }
}

chevron_right


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-

filter_none

edit
close

play_arrow

link
brightness_4
code

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")
       }
}

chevron_right


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 –

filter_none

edit
close

play_arrow

link
brightness_4
code

//main function
fun main(args: Array<String>)
{
    Add(5, 6)
    Add(5, 6, 7)
    Add(5, 6, 7, 8)
}
//class with three secondary constructors
class 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}")
    }
}

chevron_right


Output:

Sum of 5, 6 = 11
Sum of 5, 6, 7 = 18
Sum of 5, 6, 7, 8 = 26

Calling one secondary constructor from another –

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-

filter_none

edit
close

play_arrow

link
brightness_4
code

//main function
fun 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")
    }
}

chevron_right


Output:

The sum of three numbers 5,6 and 7 is: 18
The sum of two numbers 5 and 6 is: 11

Calling parent class secondary constructor from child class secondary constructor –

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

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")
    }
}

chevron_right


Output:

Employee id is: 18018
Employee name: Sagnik
Employee salary: 500000.55

Employee id is: 18018
Employee name: Sagnik


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : Akanksha_Rai



Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.