Constructors are used to initialize class properties. As in Java, a constructor is a special member function that is invoked when an object is instantiated. However, they work slightly different in Kotlin.
In Kotlin, there are two constructors:
- Primary constructor: This is a concise way to initialize the properties of a class
- Secondary constructor: This is where additional initialization logic goes
The primary constructor is part of the class header. Here's an example:
class User() {
}
The block of code surrounded by parentheses is the primary constructor. Consider the following code for 14a_PrimaryConstructor.kts:
class User(var firstName: String, var lastName: String) {
}
val user = User("Norman", "Lewis")
println("First Name= ${user.firstName}")
println("Last Name= ${user.lastName}")
The output is as follows:
The constructor goes here as part of the class header. The constructor declares two properties—firstName and lastName. Let's look at another example for 14b_PrimaryConstructor.kts:
class User(var firstName: String, val id: String) {
}
val user = User("Norman", "myId")
println("First Name = ${user.firstName}")
println("User Id = ${user.id}")
The output of the preceding code is as follows:
For the primary constructor, properties have to be declared using var or val. Otherwise, the code fails to compile.
The secondary constructor is created using the constructor keyword. The class can declare a secondary constructor to initialize its properties. This is shown in the following code:
class AuditData {
constructor(message: String) {
//init logic
}
constructor(message: String, locale: String) {
// init logic
}
}
In the preceding code snippet, we wrote two constructors. One had a message as an argument and one had two arguments—message and locale. Consider the following code for 14c_SecondaryConstructor.kts:
var audit = AuditData("record added")
println("Message ${audit.message}")
audit = AuditData("record updated", "en-US")
println("Message: ${audit.message}")
println("Locale: ${audit.locale}")
When we call AuditData with only a message, the constructor with one argument will be invoked. Similarly, when we pass two arguments, a message and a locale, the constructor with two arguments will be invoked.
The output is as follows: