Signup/Sign In

Kotlin Constructor - Primary and Secondary Constructor

In this tutorial, we will discuss the Kotlin class constructors. A constructor is used to initialize the class properties when a class object is created. It can be considered as a special function. The constructor is called itself at the time of object creation. Whenever we create an object of a class, the constructor is automatically called.

There are two types of constructors in Kotlin:

  1. Primary Constructor

  2. Secondary Constructor

There can be only one primary constructor and many secondary constructors.

Kotlin Primary Constructor

One of the most important features of Kotlin is its conciseness. It can be seen from the declaration of the primary constructor. The primary constructor is a part of the class header. All the properties of class also became part of the primary constructor.

The primary constructor is created by adding constructor() at the end of the class name:

class ClassName constructor(){
}

The constructor keyword can also be removed:

class ClassName(){
}

This means, when we define a normal class, the primary contractor gets created.

Let us create a primary constructor for the Mobile class that we created in the last tutorial:

class Mobile (var brand: String, var model: String, var mrp: Float, var discount: Float) {

    // class methods
    fun getActualPrice():Float{
        return mrp - discount
    }

    fun printDetails(){
        println("Mobile details:")
        println("Brand: $brand")
        println("Model: $model")
        println("MRP: $mrp")
        println("Discount: $discount")

    }
}

Here all the class properties are defined as the parameters of the primary constructor.

Now, let us create an object of this class:

fun main() {
    val mobile: Mobile = Mobile("iPhone", "11 pro", 100000f, 1000f)
    println("Discounted price is: ${mobile.getActualPrice()}")
    mobile.printDetails()
}


Discounted price is: 99000.0
Mobile details:
Brand: iPhone
Model: 11 pro
MRP: 100000.0
Discount: 1000.0

Now variables are initialized by the primary constructor.

But it becomes necessary to provide all the values for class properties. For that, we can also provide default values to the primary constructor:

class Mobile (var brand: String = "", var model: String = "", var mrp: Float = 0f, var discount: Float = 0f)

Primary constructor with init block

In the primary constructor, the values provided are directly assigned to the class properties. If we want to change the values before assigning them or add some logic to the primary constructor, we can use the init block.

Here is a code example,

class Mobile constructor(brand: String, model: String, mrp: Float, discount: Float) {
    var brand: String
    var model: String
    var mrp: Float
    var discount: Float

    // init function
    init {
        println("In init")
        this.brand = brand.toUpperCase()
        this.model = model.toUpperCase()
        this.mrp = mrp
        this.discount = discount
    }

    fun getActualPrice():Float{
        return mrp - discount
    }

    fun printDetails(){
        println("Mobile details:")
        println("Brand: $brand")
        println("Model: $model")
        println("MRP: $mrp")
        println("Discount: $discount")

    }
}

Now we can create the object and print details:

fun main() {
    val mobile: Mobile = Mobile("iPhone", "11 pro", 100000f, 1000f)
    println("Discounted price is: ${mobile.getActualPrice()}")
    mobile.printDetails()
}


In init
Discounted price is: 99000.0
Mobile details:
Brand: IPHONE
Model: 11 PRO
MRP: 100000.0
Discount: 1000.0

Important points regarding the init block:

  • The init block is always called after the primary constructor.

  • A class can have multiple init blocks.

Kotlin Secondary Constructor

A secondary constructor is used to initialize a group of values. The secondary constructors are created using the constructor keyword. A class can have one or more secondary constructors.

Let us create two constructors in the Mobile class:

class Mobile {
    var brand: String = ""
    var model: String = ""
    var mrp: Float = 0f
    var discount: Float = 0f

    // first secondary constructor
    constructor(_brand: String, _model: String){
        this.brand = _brand
        this.model = _model
    }

    // second secondary constructor
    constructor(_mrp: Float, _discount: Float){
        this.mrp = _mrp
        this.discount = _discount
    }

    fun getActualPrice():Float{
        return mrp - discount
    }

    fun printDetails(){
        println("Mobile details:")
        println("Brand: $brand")
        println("Model: $model")
        println("MRP: $mrp")
        println("Discount: $discount")

    }
}

Now we can create an object by passing values according to constructors:

fun main() {
    val mobile: Mobile = Mobile("iPhone", "11 pro")
    println("Discounted price is: ${mobile.getActualPrice()}")
    mobile.printDetails()
}


Discounted price is: 0.0
Mobile details:
Brand: iPhone
Model: 11 pro
MRP: 0.0
Discount: 0.0

Few points regarding secondary constructor:

  • Secondary constructors are not that common. They are generally avoided, the init blocks can be used instead to perform any specific task before object creation.

  • If the Primary constructor is already present then each secondary constructor should call the primary constructor. It is called using this():
    constructor(_brand: String, _model: String): this()

  • We can also call one secondary constructor from another secondary constructor using this():

    constructor(_brand: String, _model: String): this(10f,1f)

    This constructor is calling other constructors with values 10.0 and 1.0 for mrp and discount.

  • We can also call the constructor of the parent class (in case of inheritance) using super(). We will discuss it in the Kotlin Inheritance tutorial.

Summary

In this tutorial, we discussed constructors in Kotlin. We saw primary constructors, primary constructors with init block, and secondary constructor. We will discuss companion objects in next tutorial.



About the author:
I'm a writer at studytonight.com.