Secondary constructor

In Kotlin, like other programming languages, a class can have more than one constructor. A secondary constructor is prefixed with the constructor keyword and it is created inside the class.  

Let's take a look at the following example. The Person class contains a primary constructor with the init block and the secondary constructor with the constructor keyword:

class Person(name: String, age: Int) {
var name : String
var age : Int
var height : Double
init {
this.name = name
this.age = age
this.height = 0.0
}
constructor(name: String, age: Int, height: Double) : this(name, age) {
this.height = height
}
}

Creating a secondary constructor becomes necessary when you need to initialize a class in different ways. In this example, the Person class contains two constructors: a primary constructor that takes two parameters, and a secondary constructor that takes three parameters. The Person class can be initialized with the secondary constructor if the person's name, age, and height is available, but if the height is missing, the primary constructor can create the instance by assigning a default value to height:

class Person(name: String, age: Int) {
var name : String
var age : Int
var height : Double
init {
this.name = name
this.age = age
this.height = 0.0
}
constructor(name: String, age: Int, height: Double) : this(name, age) {
this.height = height
}
}

fun main(args: Array<String>) {
val abid = Person("Abid", 40)
println("Name ${abid.name}, Age ${abid.age}")

val igor = Person("Igor", 35, 6.0)
println("Name ${igor.name}, Age ${igor.age} Height ${igor.height}")
}

Let's have a look at how things works under the hood:

In this example, the Person class contains primary constructors with two parameters and a secondary constructor with three parameters:

val abid = Person("Abid", 40)

Creating an object with a primary constructor is straightforward. Kotlin initializes all the properties within the init block and assigns a default value of 0.0 to the height:

val igor = Person("Igor", 35, 6.0)

However, when the object is created using a secondary constructor, Kotlin calls the primary constructor using the this keyword to initialize the class properties:

constructor(name: String, age: Int, height: Double) : this(name, age) {
this.height = height
}

Once the primary constructor is called, the secondary constructor initializes the rest of the properties.

If a class contains more than one constructor, each constructor must have different parameters.

To understand the importance and the functionality of having multiple constructors in one class, let's have a look at constructor-overloading. 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.148.107.254