0

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.

2
  • 3
    You're not calling the secondary constructor. Commented Feb 26, 2020 at 8:22
  • What a silly mistake thank you for pointing out. :) Commented Feb 26, 2020 at 8:35

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

in your code val person1 = Person("Joe", 25) your are calling a constructor wich have two parameters and thats the first constructor not the second. call the second constructor like that val person1 = Person("Joe", 25,"name"). i hope that was clear.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.