I notice that classes in Kotlin can have more than one init block. If so, they are executed in sequence.
What is a good use case for having more than one?
I notice that classes in Kotlin can have more than one init block. If so, they are executed in sequence.
What is a good use case for having more than one?
请考虑以下代码片段.
class Foo() {
val x = Bar.getValue()
init {
// check the validity of x and abort if invalid
}
val y = Cow.getValue(x) // requires x to be valid
init {
// continue with initialization
}
}
由于主构造函数不能有任何代码,如果没有多个init块,上述情况就不可能发生.换句话说,拥有多个init块的能力有助于解决初始化期间涉及属性的依赖性;当属性为只读时,情况就更糟了.
Update on 10/16/2021: We can achieve the same behavior by moving the assignment of read-only (RO) properties into a single init
block. However, by doing so, we will separate the declaration of a RO property and its initialization. In comparison, multiple init
blocks help keep the declaration and initialization of RO properties together while allowing any dependent computation to follow the property initialization. Consequently, the code is a bit cleaner, easy to read/understand, and modular (as described by @mightyWOZ's reply).