Initialize read only properties from each secondary constructor

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?

I’m not sure if I understand your problem fully, but what about using a primary constructor and delegating to it from secondary constructors?

class ComplicatedType private constructor(
    val representation1: ComplicatedType1,
    val representation2: ComplicatedType2
) {
    val prop1 = heavyCalculations1(representation1)
    val propN = heavyCalculationsN(representation2)

    constructor(_representation1: ComplicatedType1) : this(_representation1, result2())
    constructor(_representation2: ComplicatedType2) : this(result1(), _representation2)
}

Also, if there are heavy calculations involved, you should consider using a factory instead. Constructors are meant to be relatively simple and lightweight.

3 Likes

It’s grate!!! I didn’t even think on private primary constructor accepting both representations!
And of course it is worth thinking on factory.
Thanks a lot!