Kotlin 简明教程

Kotlin - Constructors

Kotlin 构造函数是类中的特殊成员函数,会在实例化对象时调用。每当创建对象时,都会自动调用已定义的构造函数,用于初始化类的属性。

A Kotlin constructor is a special member function in a class that is invoked when an object is instantiated. Whenever an object is created, the defined constructor is called automatically which is used to initialize the properties of the class.

一个 Kotlin 类可能有以下两种类型的构造函数:

A Kotlin class can have following two type of constructors:

  1. Primary Constructor

  2. Second Constructors

Kotlin 类可以有一个主构造函数和一个或多个附加的辅助构造函数。Kotlin 主构造函数对类进行初始化,而辅助构造函数有助于在初始化类时包含一些额外的逻辑。

A Kotlin class can have a primary constructor and one or more additional secondary constructors. The Kotlin primary constructor initializes the class, whereas the secondary constructor helps to include some extra logic while initializing the class.

Kotlin Primary Constructor

可以像以下示例所示那样在类头级别声明主构造函数。

The primary constructor can be declared at class header level as shown in the following example.

class Person constructor(val firstName: String, val age: Int) {
   // class body
}

如果未指定任何注解或访问修饰符(如 public、private 或 protected),则可以省略 constructor 关键字。

The constructor keyword can be omitted if there is no annotations or access modifiers specified like public, private or protected..

class Person (val firstName: String, val age: Int) {
   // class body
}

在此示例中,我们已通过 val 关键字声明属性以使其为只读。如果你需要在稍后的时间点更改属性值,可以使用关键字 var 来定义这些属性。

In this example, we have declared properties through the val keyword to make them read-only. These properties could be defined using keyword var if you need to change their values at later point in time.

Initializer Block

主构造函数不能包含任何代码。可以通过 init 关键字加前缀的初始化器块来放置初始化代码。可能有多个 init 块,在实例初始化期间,初始化器块将按其在类主体中出现的顺序执行,与属性初始化器交错:

The primary constructor cannot contain any code. Initialization code can be placed in initializer blocks prefixed with the init keyword. There could be more than one init blocks and during the initialization of an instance, the initializer blocks are executed in the same order as they appear in the class body, interleaved with the property initializers:

以下是带有初始化器块用法示例:

Following is an example with a usage of initializer block:

class Person (val _name: String, val _age: Int) {
   // Member Variables
   var name: String
   var age: Int

   // Initializer Block
   init {
      this.name = _name
      this.age = _age
      println("Name = $name")
      println("Age = $age")
   }
}

fun main(args: Array<String>) {
   val person = Person("Zara", 20)
}

当你运行上述 Kotlin 程序时,它将生成以下输出:

When you run the above Kotlin program, it will generate the following output:

Name = Zara
Age = 20

Default Values

Kotlin 允许使用某些默认值初始化构造函数参数。以下是它的一个工作示例:

Kotlin allows to initialize the constructor parameters with some default values. Following is a working example for the same:

class Person (val _name: String, val _age: Int=20) {
   // Member Variables
   var name: String
   var age: Int

   // Initializer Block
   init {
      this.name = _name
      this.age = _age
      println("Name = $name")
      println("Age = $age")
   }
}

fun main(args: Array<String>) {
   val zara = Person("Zara")
   val nuha = Person("Nuha", 11)
}

当你运行上述 Kotlin 程序时,它将生成以下输出:

When you run the above Kotlin program, it will generate the following output:

Name = Zara
Age = 20
Name = Nuha
Age = 11

Kotlin Secondary Constructor

如前所述,Kotlin 允许为你的类创建一或多个辅助构造函数。利用 constructor 关键字创建该辅助构造函数。每当你在 Kotlin 中想要创建多个构造函数或每当你想要在主构造函数中包含更多逻辑且你无法执行此操作时,就需要它,因为主构造函数可能会被其他类调用。

As mentioned earlier, Kotlin allows to create one or more secondary constructors for your class. This secondary constructor is created using the constructor keyword. It is required whenever you want to create more than one constructor in Kotlin or whenever you want to include more logic in the primary constructor and you cannot do that because the primary constructor may be called by some other class.

Example

请看以下示例,在这里我们创建了一个辅助构造函数来再次实现上述示例:

Take a look at the following example, here we have created a secondary constructor to implement the above example once again:

class Person{
   // Member Variables
   var name: String
   var age: Int

   // Initializer Block
   init {
      println("Initializer Block")
   }

   // Secondary Constructor
   constructor ( _name: String, _age: Int) {
      this.name = _name
      this.age = _age
      println("Name = $name")
      println("Age = $age")
   }
}

fun main(args: Array<String>) {
   val zara = Person("Zara", 20)
}

当你运行上述 Kotlin 程序时,它将生成以下输出:

When you run the above Kotlin program, it will generate the following output:

Initializer Block
Name = Zara
Age = 20

辅助构造器不允许与辅助构造器参数配合使用 valvar 。现在让我们看一个带有两个辅助构造器的例子:

Secondary constructor do not allow to use val or var with secondary constructor parameters. Now let’s see one example with two secondary constructors:

class Person{
   // Member Variables
   var name: String
   var age: Int
   var salary:Double

   // First Secondary Constructor
   constructor ( _name: String, _age: Int) {
      this.name = _name
      this.age = _age
      this.salary = 0.00
      println("Name = $name")
      println("Age = $age")
   }

   // Second Secondary Constructor
   constructor ( _name: String, _age: Int, _salary: Double) {
      this.name = _name
      this.age = _age
      this.salary = _salary
      println("Name = $name")
      println("Age = $age")
      println("Salary = $salary")
   }
}

fun main(args: Array<String>) {
   val nuha = Person("Nuha", 12)
   val zara = Person("Zara", 20, 2000.00)
}

当你运行上述 Kotlin 程序时,它将生成以下输出:

When you run the above Kotlin program, it will generate the following output:

Name = Nuha
Age = 12
Name = Zara
Age = 20
Salary = 2000.0