I need to initialize a lot of read only properties from each secondary constructor, but don’t want to duplicate initialization code.
Something like this:
class ComplicatedType {
val representation1: ComplicatedType1
val representation2: ComplicatedType2
val prop1 // error: Property must be initialized or be abstract
// a lot of similar properties
// ...
val propN // error Property must be initialized or be abstract
constructor(_representation1: ComplicatedType1) {
representation1 = _representation1
// a lot of work to create representation2 from representation1
// ...
representation2 = result2()
initializeAllProperties()
}
constructor(_representation2: ComplicatedType2) {
representation2 = _representation2
// a lot of work to create representation1 from representation2
// ...
representation1 = result1()
initializeAllProperties()
}
fun initializeAllProperties() {
prop1 = heavyCalculations1(representation1) // Error: Val cannot be reassigned
// ...
propN = heavyCalculationsN(representation2) // Error: Val cannot be reassigned
}
}
It seems that current language design don’t allow this. Is there any reasonable way to accomplish the task?