Kotlin二级构造函数教程

441 阅读2分钟

在Kotlin中,有两种方式可以在class 中创建构造函数。

一种方式是使用主构造函数,如下图所示,class 属性在class 头部被初始化:

class Person(
val name: String
)

在上面的例子中,Person 类的name: String 属性在主构造函数中被初始化了。

另一种创建构造函数的方法是定义一个二级构造函数

class 初级构造函数只允许你初始化类的属性,而次级构造函数允许你编写一些逻辑,在类的对象被初始化时执行。

考虑一下下面的例子:

class Person {
constructor(name: String) {
println("Hello, my name is $name")
}
}
Person("Nathan")
// Hello, my name is Nathan

在上面的例子中,一个二级构造函数是用关键字constructor() ,后面是构造函数体来声明的。

这类似于创建普通函数的方式,但这个函数使用关键字constructor ,而不是fun ,并且没有名字(匿名)。

下面是一个Kotlinclass ,它的一级构造函数与上面的例子相等:

class Person(name: String) {
init {
println("Hello, my name is $name")
}
}

但是,虽然二级构造函数可以在没有init 块的情况下执行代码逻辑,但你不能在二级构造函数中声明class 属性。

下面的代码将触发一个错误:

class Person {
 constructor(val name: String, var age: Int) {
 println("Hello, my name is $name")
}
}
// Error: 'val' on secondary constructor parameter is not allowed
// Error: 'var' on secondary constructor parameter is not allowed

不创建主构造函数,你需要在主体中声明class 属性:

class Person {
 var name: String
 constructor(name: String) {
this.name = name
println("Hello, my name is $name")
}
}
val person = Person("Nathan")
person.name = "Joy"

上面的例子表明,当你在没有主构造函数的情况下创建一个二级构造函数时,是相当多余的。

这就是为什么大多数时候,你只需要使用主构造函数并从init 块中运行一些逻辑。

你也可以在一个class 中添加多个二级构造函数,如下图所示:

class Person {
 constructor(name: String) {
 println("1st secondary constructor called")
println("Hello, my name is $name")
}
 constructor(name: String, age: Int) {
 println("2nd secondary constructor called")
println("Hello, my name is $name")
println("I'm $age years old")
}
}
Person("Nathan")
// 1st secondary constructor called...
Person("Joy", 23)
// 2nd secondary constructor called...

Kotlin会根据你发送给带有多个二级构造函数的class 的参数来决定执行哪个constructor

最后,你可以让一个Kotlinclass 同时具有主要构造函数和次要构造函数,但有一个条件,即你要从次要构造函数中调用主要构造函数。

请看下面的例子:

class Person(val name: String) {
 constructor(name: String, age: Int) : this(name) {
 println("Secondary constructor called")
}
}
Person("Nathan")
// prints nothing
Person("Naomi", 25)
// Secondary constructor called

二级构造函数通过在二级构造函数的参数后面使用: this(name) 语法来调用一级构造函数。

另外,你不能有两个参数相同的构造函数,所以二级构造函数需要有不同的参数。

如果这看起来让你感到困惑,那是因为它是 😄

class 中创建二级构造函数,可以让你更灵活地定义从object ,可以创建哪些class

但代价是,你将增加代码的复杂性,使其更难维护和开发。

我建议你使用主构造函数,直到你有充分的理由使用辅助构造函数。

在学习Kotlinclass 二级构造函数方面做得很好!👍