Issue
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?
Solution
Consider the following snippet.
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
}
}
Since primary constructor cannot have any code, the above situation would not be possible without multiple init blocks. In other words, the ability to have multiple init blocks helps tackle dependencies involving properties during initialization; more so, when properties are read-only.
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).
Answered By - Venkatesh-Prasad Ranganath
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.