Question - What is a primary constructor in Kotlin?
Answer -
In Kotlin, the primary constructor is a part of the class header. Unlike Java, it doesn't need you to declare a constructor in the body of the class.
Kotlin facilitates you to declare the constructor in the class header itself:
See the following example:
class Person constructor(name: String, age: Int, salary: Int) {
}
Just like functions or methods, it takes a series of parameters with their type. These parameters initialize the variables present in the class.
If you do not have any annotations or modifiers (public, private, protected), you can omit the constructor keyword like the following example.
class Person (name: String, age: Int, salary: Int) {
}
By removing the constructor keyword, you can get code that is simplified and easy to understand.