Search code examples
androidkotlinconstructorprimary-constructor

How to access primary constructor parameters inside secondary constructor kotlin


I am learning kotlin and I was reading about constructors: primary and secondary.

Here is my question that how should I access primary constructor parameters inside a secondary constructor. I am unable to access but I am not sure why? Why I am not able to access it directly?
If anyone knows please help me understand this concept in a better way. Why I am not able to access it?

I have created one demo class with two constructors here is my code:

fun main(args: Array<String>) {

    val person1 = Person("Joe", 25)
    println("First Name = ${person1.firstName}") // working, printing first name 

}

class Person(val firstName: String, var age: Int) {

    constructor(sectionName: String, id: Int, name: String) : this(sectionName,id)  {
        println("Age = ${age}") // not working, no output
    }

}

Or Am I doing anything wrong?

PS: I know I can write init block and assign the parameters to the class variable and it is working as expected.


Solution

  • You have to call your secondary constructor, which expects a trailing name parameter:

        val person1 = Person("Joe", 25, "name") //prints Age = 25
        val person2 = Person("Joe", 25) //prints nothing
    

    In your example, the primary constructor gets chosen as your argument list maps its parameters.