Bird
Raised Fist0
Kotlinprogramming~10 mins

Secondary constructors in Kotlin - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Secondary constructors
Class Declaration
↓
Primary Constructor?
Yes→Initialize Primary
↓
Secondary Constructor
↓
Call Primary or Another Secondary
↓
Initialize Properties
↓
Object Created
Shows how Kotlin class creation flows through primary and secondary constructors, with secondary constructors calling primary or other secondary ones before initializing.
Execution Sample
Kotlin
class Person(val name: String) {
    var age: Int = 0
    constructor(name: String, age: Int) : this(name) {
        this.age = age
    }
}

val p = Person("Anna", 25)
Creates a Person object using a secondary constructor that sets name and age.
Execution Table
StepActionConstructor CalledProperty ValuesNotes
1Create Person("Anna", 25)Secondary constructor (name, age)name=uninitialized, age=0Start secondary constructor
2Call primary constructor with name="Anna"Primary constructor (name)name="Anna", age=0Primary constructor initializes name
3Execute secondary constructor bodySecondary constructor (name, age)name="Anna", age=25Secondary constructor sets age
4Object creation completePerson instancename="Anna", age=25Person object ready
💡 Secondary constructor calls primary constructor first, then sets additional properties, finishing object creation.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
nameuninitializeduninitialized"Anna""Anna""Anna"
age0002525
Key Moments - 3 Insights
Why does the secondary constructor call the primary constructor first?
Because in Kotlin, every secondary constructor must delegate to the primary constructor (directly or indirectly) to ensure the base properties are initialized properly, as shown in execution_table step 2.
What happens if the secondary constructor does not call the primary constructor?
The code will not compile. Kotlin requires secondary constructors to delegate to the primary constructor to maintain consistent initialization, as seen in the flow and step 2 of the execution_table.
When is the property 'age' set in the example?
The 'age' property is set in the body of the secondary constructor after the primary constructor has initialized 'name', as shown in execution_table step 3.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of 'name' after step 2?
A"Anna"
Buninitialized
Cnull
D25
💡 Hint
Check the 'Property Values' column in execution_table row for step 2.
At which step does the secondary constructor set the 'age' property?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Look at the 'Notes' column in execution_table for when 'age' changes.
If the secondary constructor did not call the primary constructor, what would happen?
AThe object is created without 'name'
BCompilation error occurs
CThe program runs normally
DThe secondary constructor is ignored
💡 Hint
Refer to key_moments about constructor delegation requirement.
Concept Snapshot
Secondary constructors in Kotlin allow multiple ways to create objects.
Each secondary constructor must call the primary constructor.
Primary constructor initializes main properties.
Secondary constructors add or override initialization.
This ensures consistent object setup.
Full Transcript
In Kotlin, a class can have a primary constructor and one or more secondary constructors. When you create an object using a secondary constructor, Kotlin requires that this constructor calls the primary constructor first. This ensures that the main properties defined in the primary constructor are initialized properly. After calling the primary constructor, the secondary constructor can set additional properties or perform extra setup. For example, in the Person class, the secondary constructor takes both name and age. It calls the primary constructor with name, then sets the age property. This flow guarantees that the object is fully and correctly initialized before it is used.

Practice

(1/5)
1. What is the main purpose of a secondary constructor in Kotlin?
easy
A. To create static methods
B. To replace the primary constructor completely
C. To provide additional ways to create an object with different parameters
D. To define functions inside a class

Solution

  1. Step 1: Understand constructors in Kotlin

    Kotlin classes can have a primary constructor and one or more secondary constructors to create objects.
  2. Step 2: Role of secondary constructors

    Secondary constructors allow creating objects with different sets of parameters, providing flexibility.
  3. Final Answer:

    To provide additional ways to create an object with different parameters -> Option C
  4. Quick Check:

    Secondary constructors = multiple ways to create objects [OK]
Hint: Secondary constructors add extra ways to create objects [OK]
Common Mistakes:
  • Thinking secondary constructors replace the primary constructor
  • Confusing constructors with functions
  • Assuming secondary constructors create static methods
2. Which of the following is the correct syntax for a secondary constructor in Kotlin?
easy
A. secondary constructor(name: String) { this.name = name }
B. fun constructor(name: String) { this.name = name }
C. init constructor(name: String) { this.name = name }
D. constructor(name: String) { this.name = name }

Solution

  1. Step 1: Recall Kotlin secondary constructor syntax

    Secondary constructors use the keyword constructor followed by parameters and a body.
  2. Step 2: Check each option

    constructor(name: String) { this.name = name } uses correct syntax: constructor(name: String) { ... }. Others use invalid keywords.
  3. Final Answer:

    constructor(name: String) { this.name = name } -> Option D
  4. Quick Check:

    Keyword 'constructor' starts secondary constructors [OK]
Hint: Look for 'constructor' keyword without fun or init [OK]
Common Mistakes:
  • Adding 'fun' before constructor
  • Using 'secondary' keyword
  • Confusing with init blocks
3. What will be the output of the following Kotlin code?
class Person(val name: String) {
    var age: Int = 0
    constructor(name: String, age: Int) : this(name) {
        this.age = age
    }
}

fun main() {
    val p = Person("Alice", 30)
    println("Name: ${p.name}, Age: ${p.age}")
}
medium
A. Name: Alice, Age: 0
B. Name: Alice, Age: 30
C. Name: , Age: 30
D. Compilation error

Solution

  1. Step 1: Understand constructor calls

    The secondary constructor calls the primary constructor with this(name), initializing name.
  2. Step 2: Assign age in secondary constructor

    The secondary constructor sets this.age = age, so age becomes 30.
  3. Final Answer:

    Name: Alice, Age: 30 -> Option B
  4. Quick Check:

    Secondary constructor sets age correctly [OK]
Hint: Secondary constructor calls primary, then sets extra properties [OK]
Common Mistakes:
  • Assuming age stays 0
  • Thinking name is empty
  • Expecting compilation error
4. Identify the error in this Kotlin class with a secondary constructor:
class Car(val model: String) {
    constructor(model: String, year: Int) {
        println("Year: $year")
    }
}
medium
A. Secondary constructor must call the primary constructor
B. Cannot assign to val property 'model'
C. Missing return type in secondary constructor
D. println cannot be used inside constructor

Solution

  1. Step 1: Check secondary constructor rules

    In Kotlin, a secondary constructor must delegate to the primary constructor using : this(...).
  2. Step 2: Analyze given code

    The secondary constructor does not call this(model), so it violates the rule.
  3. Final Answer:

    Secondary constructor must call the primary constructor -> Option A
  4. Quick Check:

    Secondary constructors require delegation [OK]
Hint: Always delegate secondary constructors to primary with ': this(...)' [OK]
Common Mistakes:
  • Forgetting to delegate to primary constructor
  • Trying to assign val property directly
  • Thinking println is disallowed
5. You want to create a Kotlin class Book with a primary constructor that takes title and a secondary constructor that also takes author. The secondary constructor should reuse the primary constructor and set author. Which code correctly implements this?
hard
A. class Book(val title: String) { var author: String = "Unknown" constructor(title: String, author: String) : this(title) { this.author = author } }
B. class Book(val title: String, var author: String) { constructor(title: String) { this.title = title this.author = "Unknown" } }
C. class Book(val title: String) { constructor(title: String, author: String) { this.title = title this.author = author } }
D. class Book { constructor(title: String) { this.title = title } constructor(title: String, author: String) { this.title = title this.author = author } }

Solution

  1. Step 1: Check primary constructor and property initialization

    class Book(val title: String) { var author: String = "Unknown" constructor(title: String, author: String) : this(title) { this.author = author } } defines primary constructor with title and a mutable author property with default value.
  2. Step 2: Verify secondary constructor delegates properly

    The secondary constructor calls : this(title) to reuse primary constructor and sets author inside its body.
  3. Final Answer:

    class Book(val title: String) { var author: String = "Unknown" constructor(title: String, author: String) : this(title) { this.author = author } } -> Option A
  4. Quick Check:

    Secondary constructor delegates and sets extra property [OK]
Hint: Secondary constructors must delegate and set extra properties inside body [OK]
Common Mistakes:
  • Not delegating secondary constructor to primary
  • Trying to assign val properties
  • Missing property initialization
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard