WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Kotlin · Intermediate · question 34 of 100

Explain the difference between primary and secondary constructors in Kotlin. How can you call a secondary constructor from a primary constructor?

📕 Buy this interview preparation book: 100 Kotlin questions & answers — PDF + EPUB for $5

In Kotlin, a class can have one primary constructor and one or more secondary constructors. The primary constructor is defined as part of the class header and is responsible for initializing the class.

On the other hand, secondary constructors are defined inside the class body and provide an additional way to initialize class properties. Secondary constructors are optional, and if they are present, they must directly or indirectly delegate to the primary constructor.

A class with a primary constructor:

class Person(firstName: String, age: Int) {
    // Class properties
    val firstName: String
    val age: Int

    init {
        // Initialize class properties in the primary constructor
        this.firstName = firstName
        this.age = age
    }
}

A class with both primary and secondary constructors:

class Person {
    // Class properties
    val firstName: String
    val age: Int

    constructor(firstName: String) {
        // Initialize a few properties in the secondary constructor
        this.firstName = firstName
        this.age = 0
    }

    constructor(firstName: String, age: Int) {
        // Initialize all the properties in the secondary constructor
        this.firstName = firstName
        this.age = age
    }
}

To call a secondary constructor from a primary constructor in Kotlin, we can use the ‘this‘ keyword along with the required arguments. Here is an example:

class Person(firstName: String) {
    val lastName: String

    constructor(firstName: String, lastName: String) : this(firstName) {
        // call to primary constructor to initialize firstName
        this.lastName = lastName
    }
}

In the above example, we have defined a secondary constructor that takes two arguments, ‘firstName‘ and ‘lastName‘. This constructor calls the primary constructor using the ‘this‘ keyword, passing only the ‘firstName‘ argument. After that, we can initialize ‘lastName‘ in the body of the secondary constructor. By doing this, we avoid duplicating the initialization logic of ‘firstName‘, which has already been done in the primary constructor.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Kotlin interview — then scores it.
📞 Practice Kotlin — free 15 min
📕 Buy this interview preparation book: 100 Kotlin questions & answers — PDF + EPUB for $5

All 100 Kotlin questions · All topics