Search code examples
statickotlincompanion-object

Kotlin object vs companion-object vs package scoped methods


I have written this methods in Kotlin and analysed the bytecode:

Situation 1

class A {
    object b {
        fun doSomething() {}
    }
}

Situation 2

class A {
    companion object b {
        fun doSomething() {}
    }
}

Situation 3

fun doSomething() {}

Bytecode Result

  • Situation 1: class Test$asb, public final doSomething()I
  • Situation 2: class Test$Companion, public final doSomething()I
  • Situation 3: class TestKt, public final static doSomething()I

My questions are:

  • I have an enum class, and I want to return an enum instace given an enum variable, for instance, findById (enum(id, color)). How would I do it? Companion Object? object?

  • It seems the only way to have a real static method is in package level, without class declaration. But that becomes a little bit too global. Is there any way to access it via: ClassName.staticMethod, staticMethod being really static.

  • Provide meaningfull examples of package declaration methods, companion object and object.

Context. I have been coding in Kotlin and I find it amazing. But sometimes I need to make a decision: for example, a heavy immutable property which in java I would declare as static final, but in Kotlin I find it hard to "find an equivalent".


Solution

  • I would suggest to develop voddan answer:

    enum class Color {
    
        RED,
        BLUE,
        GREEN;
    
    
        companion object Utils {
            fun findById(color: Color): Color {
                return color;
            }
        }
    }
    

    And to test

    @Test
    fun testColor() {
        println(Color.Utils.findById(Color.valueOf("RED")));
    }