Recall & Review
beginner
What is a secondary constructor in Kotlin?
A secondary constructor is an additional constructor in a Kotlin class that allows creating objects with different sets of parameters besides the primary constructor.Click to reveal answer
beginner
How do you declare a secondary constructor in Kotlin?
Use the keyword <code>constructor</code> inside the class body, followed by parameters and an optional call to the primary constructor using <code>this()</code>.Click to reveal answer
intermediate
Why would you use a secondary constructor instead of just a primary constructor with default parameters?
Secondary constructors let you provide different ways to create an object when default parameters are not enough or when you want to run different initialization code.Click to reveal answer
intermediate
What must a secondary constructor do if the class has a primary constructor?It must delegate to the primary constructor either directly or indirectly by calling
this() with appropriate arguments.Click to reveal answer
beginner
Example: What does this Kotlin code do?<br><pre>class Person(val name: String) {
constructor(name: String, age: Int) : this(name) {
println("Age is $age")
}
}</pre>It defines a class
Person with a primary constructor taking name. The secondary constructor takes name and age, calls the primary constructor with name, and prints the age.Click to reveal answer
In Kotlin, how do you declare a secondary constructor?
✗ Incorrect
Secondary constructors are declared with the
constructor keyword inside the class body.What must a secondary constructor do if the class has a primary constructor?
✗ Incorrect
A secondary constructor must delegate to the primary constructor using
this().Which of these is a reason to use a secondary constructor?
✗ Incorrect
Secondary constructors provide alternative ways to create objects with different parameters.
Can a Kotlin class have multiple secondary constructors?
✗ Incorrect
Kotlin allows multiple secondary constructors in a class.
What happens if a secondary constructor does not delegate to the primary constructor in a class that has one?
✗ Incorrect
Kotlin requires secondary constructors to delegate to the primary constructor; otherwise, it causes a compilation error.
Explain what a secondary constructor is in Kotlin and when you might use it.
Think about creating objects with different parameters or initialization.
You got /3 concepts.
Describe the rules for delegation between secondary and primary constructors in Kotlin.
Focus on how constructors connect inside the class.
You got /3 concepts.