Q23. What is the difference between a primary and a secondary constructor?
The primary constructor is part of the class header and is where you declare and often initialize properties directly (class User(val name: String)). Secondary constructors are declared inside the body with the constructor keyword and must delegate to the primary one with this(...).
The init block holds setup logic that runs with the primary constructor. Most Kotlin classes need only a primary constructor plus default arguments, so secondary constructors are less common than in Java.
class User(val name: String, val age: Int) {
init {
require(age >= 0) { "age must be non-negative" }
}
constructor(name: String) : this(name, 0) // delegates to primary
}