- Kotlin for Enterprise Applications using Java EE
- Raghavendra Rao K
- 341字
- 2021-06-10 18:49:22
Constructors
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:
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:
- 大話PLC(輕松動漫版)
- Docker技術入門與實戰(第3版)
- 編程卓越之道(卷3):軟件工程化
- ANSYS Fluent 二次開發指南
- Visual Basic程序設計
- Python算法詳解
- Unity Character Animation with Mecanim
- Python期貨量化交易實戰
- Training Systems Using Python Statistical Modeling
- Machine Learning for OpenCV
- 深度學習入門:基于Python的理論與實現
- SFML Game Development
- PHP Microservices
- Processing開發實戰
- JSP應用與開發技術(第3版)