官术网_书友最值得收藏!

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:

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 localeConsider 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:

主站蜘蛛池模板: 军事| 买车| 桐乡市| 乐都县| 华阴市| 神木县| 花莲县| 林芝县| 延边| 渝中区| 望城县| 翁牛特旗| 奉化市| 崇仁县| 定兴县| 沁源县| 津市市| 鸡东县| 吕梁市| 大余县| 礼泉县| 嵊泗县| 晋城| 双鸭山市| 尉犁县| 青州市| 林芝县| 宁陕县| 达尔| 安庆市| 循化| 延长县| 临西县| 丹凤县| 拉孜县| 本溪市| 尚义县| 金坛市| 修武县| 巴塘县| 昂仁县|