Split a companion object's code into several places to organize class and companion fields

Kotlin uses companion objects instead of static fields in Java. In Java, there are cases where some member fields have a close relation with some static fields so you group them together. For example, it may be possible that it is natural order in logic to first understand some static fields that lead to some member fields, then those member field, then some other static fields that give additional information. Since in Kotlin, you have to put all companion fields in a companion object and it can’t be split, it becomes impossible to do so.

Is supporting splitting a companion object’s code into several places a solution? Or are there better approaches?

You can declare close related fields in interfaces, define fields values in interface implementing classes and then combine them in a companion object using interfaces multiple inheritance and delegation.

class SomeClass {

    fun someMethod() {
        valOne
        valTwo
    }

    companion object :
        UnitOne by UnitOneImpl(),
        UnitTwo by UnitTwoImpl()
}

interface UnitOne {
    val valOne: Int
}

class UnitOneImpl : UnitOne {
    override val valOne = 1
}

interface UnitTwo {
    val valTwo: Long
}

class UnitTwoImpl : UnitTwo {
    override val valTwo = 2L
}
2 Likes

I think the original post probably meant something like https://youtrack.jetbrains.com/issue/KT-19954 or https://youtrack.jetbrains.com/issue/KT-11420

1 Like