Bird
Raised Fist0
Kotlinprogramming~20 mins

Secondary constructors in Kotlin - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Secondary Constructor Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of secondary constructor call
What is the output of this Kotlin code using a secondary constructor?
Kotlin
class Person(val name: String) {
    var age: Int = 0

    constructor(name: String, age: Int) : this(name) {
        this.age = age
    }

    fun info() = "$name is $age years old"
}

fun main() {
    val p = Person("Alice", 30)
    println(p.info())
}
AAlice is 30 years old
BAlice is 0 years old
CRuntime error: Uninitialized property
DCompilation error due to secondary constructor
Attempts:
2 left
💡 Hint
Remember that the secondary constructor calls the primary constructor first.
❓ Predict Output
intermediate
2:00remaining
Value of property after secondary constructor
What is the value of 'age' after creating an instance with the secondary constructor?
Kotlin
class Animal(val species: String) {
    var age: Int = 5

    constructor(species: String, age: Int) : this(species) {
        this.age = age
    }
}

fun main() {
    val a = Animal("Dog", 7)
    println(a.age)
}
A7
B5
C0
DCompilation error
Attempts:
2 left
💡 Hint
Check how the secondary constructor sets the 'age' property.
🔧 Debug
advanced
2:00remaining
Identify the error in secondary constructor usage
What error does this Kotlin code produce?
Kotlin
class Car(val brand: String) {
    var year: Int

    constructor(brand: String, year: Int) {
        this.brand = brand
        this.year = year
    }
}

fun main() {
    val c = Car("Toyota", 2020)
    println(c.brand + " " + c.year)
}
ACompilation error: Val cannot be reassigned
BRuntime error: Uninitialized property 'year'
CCompilation error: Secondary constructor must delegate to primary
DNo error, prints 'Toyota 2020'
Attempts:
2 left
💡 Hint
Check how the secondary constructor calls the primary constructor.
📝 Syntax
advanced
2:00remaining
Correct syntax for secondary constructor delegation
Which option shows the correct syntax for a secondary constructor delegating to the primary constructor?
Kotlin
class Book(val title: String) {
    var pages: Int = 0

    // Secondary constructor here
}
Aconstructor(title: String, pages: Int) { this.pages = pages }
Bconstructor(title: String, pages: Int) : this(title) { this.pages = pages }
Cconstructor(title: String, pages: Int) -> this(title) { this.pages = pages }
Dconstructor(title: String, pages: Int) : super(title) { this.pages = pages }
Attempts:
2 left
💡 Hint
Look for the correct delegation syntax using ': this(...)'.
🚀 Application
expert
2:00remaining
Number of instances created with secondary constructor
Given this Kotlin code, how many times is the primary constructor called when creating an instance with the secondary constructor?
Kotlin
class User(val username: String) {
    init {
        println("Primary constructor called for $username")
    }

    constructor(username: String, email: String) : this(username) {
        println("Secondary constructor called for $username with email $email")
    }
}

fun main() {
    val u = User("john_doe", "john@example.com")
}
APrimary constructor is called after secondary constructor
BPrimary constructor is called twice
CPrimary constructor is not called
DPrimary constructor is called once
Attempts:
2 left
💡 Hint
Remember how secondary constructors delegate to primary constructors in Kotlin.

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