Kotlin Secondary Constructor (AKA Constructor Overloading) Tutorial

In this section, we will learn what the constructor overloading is and how it works in Kotlin.

Note: we’re assuming you’re already familiar with the Kotlin constructor.

What is Secondary Constructor in Kotlin?

The secondary constructors in Kotlin are a way of creating over one constructor for a class with different set of parameters.

This way, we have the option of choosing the right constructor for our object with the right number of arguments when creating an object from that class.

How to Create a Secondary Constructor in Kotlin? Constructor Overloading Syntax:

This is the syntax of creating a secondary constructor in Kotlin:

constructor (param1:data-type, param_n: data-type){…}

constructor: in order to create a secondary constructor, we start with the keyword constructor and then put any number of parameters inside the pair of parentheses that comes after the keyword.

Also note that the secondary constructors have bodies as well. This means if you have properties in your class, you can initialize them within the body of these constructors.

The syntax above is used when the target class does not have a primary constructor. But if the class also had a primary constructor, then we should defer to that constructor instead.

This means somehow we need to call the primary constructor via the secondary constructor and pass its required arguments. Otherwise we will get an error.

This is how we can defer to the primary constructor:

constructor (param1:data-type, param_n: data-type) this(arg1, arg2, argN){…}

The :this keyword and the pair of parentheses that come after is a call to the primary constructor. So the arguments we set for this call must be equal to the number of parameters that the primary constructor has. (We will see an example of it in just a moment. )

Note: when a secondary constructor defers to a primary constructor, first it’s the primary constructor that will be executed, but then the body of the secondary constructor will be executed as well.

Example: creating a secondary constructor in Kotlin

class Person (var firstName:String, var lastName:String, var id:Int ,var company: String) {

    init{
        println("This is a message that comes from the initializer block")
    }
    constructor(name:String, lastName:String, company:String): this(name,lastName, 0 ,company){
        println("This is a message that comes from the secondary constructor")
    }
    constructor(name:String= "John", lastName:String= "Doe", id:Int= 0) : this(name,lastName, id,"Apple"){
        println("This is a message that comes from the second secondary constructor")
    }
}

fun main(){

    var person = Person("Jack","Bauer", "Google")
    println("The name of the person is ${person.firstName} its last name is ${person.lastName} and its id is ${person.id} and the name of the company is: ${person.company}")

    var prs2 = Person() 
    println("The name of the person is ${prs2.firstName} its last name is ${prs2.lastName} and its id is ${prs2.id} and the name of the company is: ${prs2.company}")

}

Output:

This is a message that comes from the initializer block

This is a message that comes from the secondary constructor

The name of the person is Jack its last name is Bauer and its id is 0 and the name of the company is: Google

This is a message that comes from the initializer block

This is a message that comes from the second secondary constructor

The name of the person is John its last name is Doe and its id is 0 and the name of the company is: Apple

How Doe Secondary Constructor Work in Kotlin?

Here we have two secondary constructors and one primary constructor. As you can see, both secondary constructors deferred to the primary constructor using the :this keyword and passing 4 arguments to it.

Here you can see, the first secondary constructor takes 3 arguments. So if we want to create an object from this class and we have only 3 arguments to pass to the constructor, then this is the one that will be invoked. It will then pass its parameters as the argument for the primary constructor and also set a default value for the id parameter of the primary constructor because it didn’t have a user set value for it.

The other secondary constructor takes 3 optional arguments! This means if you create a class but didn’t pass any value to its constructor, then Kotlin invokes this constructor because it has optional parameters and that means even without passing an argument to it, it still would work. (The second object we’ve created here was based on this constructor).

Example: creating a secondary constructor without primary constructor

class Person {
    var name: String 
    var lastName: String
    var id: Int

    constructor(name:String, lastName:String = "Doe ", id:Int = 0){
        this.name = name
        this.lastName = lastName
        this.id = id 
        
    }
}

fun main(){

    var person = Person("Jack","Bauer",200)
    println("The name of the person is ${person.name} its last name is ${person.lastName} and its id is ${person.id}")
}

Output:

The name of the person is Jack its last name is Bauer and its id is 200

Here, as you can see, there’s no primary constructor set for the class and we have only one secondary constructor. So there’s no need to call the this keyword to defer to the primary constructor anymore.

Also note that when creating an object from this class, we still need to pass at least one argument to the constructor (Because the other two have their own default values for this example)! Otherwise we will get an error.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies