问题描述
我已经开始学习Kotlin。我想知道 init
块和构造函数
之间的区别。
它和我们如何使用它来改善之间有什么区别?
I have started learning Kotlin. I would like to know the difference between init
block and constructor
.What is the difference between this and how we can use this to improve?
class Person constructor(var name: String, var age: Int) {
var profession: String = "test"
init {
println("Test")
}
}
推荐答案
init 块将在主要构造函数之后立即执行。初始化程序块实际上成为主构造函数的一部分。 构造函数是辅助构造函数。委派给主要构造函数的过程是次要构造函数的第一条语句,因此所有初始化程序块中的代码都在次要构造函数主体之前执行。
The init block will execute immediately after the primary constructor. Initializer blocks effectively become part of the primary constructor. The constructor is the secondary constructor. Delegation to the primary constructor happens as the first statement of a secondary constructor, so the code in all initializer blocks is executed before the secondary constructor body.
示例
class Sample(private var s : String) {
constructor(t: String, u: String) : this(t) {
this.s += u
}
init {
s += "B"
}
}
认为您使用以下示例初始化了Sample类
Think you initialized the Sample class with
Sample("T","U")
您将获得一个变量 s 处的字符串响应为 TBU
。
值 T
是从 Sample 类的主要构造函数分配给 s 的,然后立即init块开始执行,它将在变量中添加 B
。在初始化块之后,辅助构造函数块开始执行,并且 s 将变为 TBU
。
You will get a string response at variable s as "TBU"
.Value "T"
is assigned to s from the primary constructor of Sample class, and then immediately init block starts to execute it will add "B"
to the variable. After init block secondary constructor block starts to execute and s will become "TBU"
.
这篇关于int块和kotlin中的构造函数有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!