Kotlin Constructors

This post is about constructors in Kotlin. I recommend you to read my post about Kotlin Classes before reading this.

Constructors are functions associated with a class, that are run automatically when the objects are created to initialize the properties of that object. In Kotlin there are two types of constructors. Default constructor and custom constructor.

kotlin constructors
kotlin constructors

Let’s take a look at a class without a constructor:

class data1 {
    var prop1 = 0
    var prop2 = 0
    fun printValues() {
        println("Property1 : $prop1")
        println("Property2 : $prop2")
    }
}

fun main(args: Array<String>) {
    val obj1 = data1()
    obj1.prop1 = 10
    obj1.prop2 = 20
    obj1.printValues()
}

The function has two properties, prop1 and prop2. They are initialized with value 0 when they’re declared.
We create an object of the class in the main function. After the object is created, the values of the two properties are 0. Then we change it to values 10 and 20. Then the function printValues is called on the object, which prints the values of the properties.

This is not something that we want. We want the initial values of the properties to come from where the objects are created. The solution is using constructors.

Now, let’s write the above program using constructor.

class data1(p1: Int, p2: Int) {
    var prop1 = p1
    var prop2 = p2
    fun printValues() {
        println("Property1 : $prop1")
        println("Property2 : $prop2")
    }
}

fun main(args: Array<String>) {
    val obj1 = data1(10, 20)
    obj1.printValues()
}

Now, we’ve added a constructor. See what we’ve written inside the parenthesis. (p1: Int, p2: Int) this is our primary constructor. When the object is created like this val obj1 = data1(10, 20). The value 10 and 20 are passed to the constructor. Later it gets assigned to the properties of the object (prop1 and prop2). Now, this is a basic constructor. But it’s not the best way to use primary constructors. We can make the code even more concise.
Look at this.

class data1(var prop1: Int, var prop2: Int) {
    fun printValues() {
        println("Property1 : $prop1")
        println("Property2 : $prop2")
    }
}

fun main(args: Array<String>) {
    val obj1 = data1(10, 20)
    obj1.printValues()
}

What is the difference? We added the var keyword to the constructor parameters. Now they are constructor parameters as well as properties of the class. We don’t have to declare those properties again. Really smart! Isn’t it?

Default Parameters in Constructors

Like functions, we can have default values for constructor parameters.

class data1(var prop1: Int, var prop2: Int, var prop3: String = "Default") {
    fun printValues() {
        println("Property1 : $prop1")
        println("Property2 : $prop2")
        println("Property3 : $prop3")
    }
}

fun main(args: Array<String>) {
    val obj1 = data1(10, 20)
    val obj2 = data1(11, 21, "Not default")
    obj1.printValues()
    obj2.printValues()
}

Initialization Block

Primary constructors in Kotlin can’t contain any code. If you need to do some validation or something, you can’t do inside the primary constructor as it is only a list of parameters. Kotlin has something called an initialization block as a solution to this problem.
Initialization block is nothing but a block of code that runs automatically when objects are created.

class data1(var prop1: Int, var prop2: Int, var prop3: String = "Default") {
    init {
        if(prop1 !in 10..20)
            prop1=15
    }
    fun printValues() {
        println("Property1 : $prop1")
        println("Property2 : $prop2")
        println("Property3 : $prop3")
    }
}

fun main(args: Array<String>) {
    val obj1 = data1(35, 20)
    val obj2 = data1(11, 21, "Not default")
    obj1.printValues()
    obj2.printValues()
}

Secondary Constructors in Kotlin

Besides primary constructors and initialization blocks, there are secondary constructors in Kotlin. We use the keyword constructor for defining secondary constructors. In secondary constructor, we can have any number of executable code. We can have more than one secondary constructor. It gets called like overloaded functions.

class data1(var prop1: Int, var prop2: Int, var prop3: String = "Default") {
    var prop4 : String = ""
    init {
        if(prop1 !in 10..20)
            prop1=15
    }
    constructor(p1:Int, p2:Int,p3:String,p4 : String):this(p1,p2,p3){
    prop4 = if(p4=="") "Hello" else p4
    }
    fun printValues() {
        println("Property1 : $prop1")
        println("Property2 : $prop2")
        println("Property3 : $prop3")
        println("Property4 : $prop4")
    }
}

fun main(args: Array<String>) {
    val obj1 = data1(35, 20)
    val obj2 = data1(11, 21, "Not default")
    val obj3 = data1(22,33,"Not default","Hello there!")
    obj1.printValues()
    obj2.printValues()
    obj3.printValues()
}

As you can see, the secondary constructor gets called when we create an object with four parameters. It does a validation inside the constructor. As we said earlier, it is allowed to have executable code inside the secondary constructor.

That’s about constructors in Kotlin. Hope you understood the concept.

Comments and feedback are welcome.

Happy Coding đŸ™‚

« Back to the index of Kotlin tutorial

Please follow and like us:

Leave a Reply