Sobes.tech
Middle

What is the difference between an object inside a class and a companion object in Kotlin?

sobes.tech AI

Answer from AI

An object inside a class (inner object) is bound to an instance of the outer class and exists only within its lifecycle. A companion object exists as a singleton, not bound to an instance of the class, and can be accessed directly via the class name.

Main differences:

  • Binding to an instance: inner object is bound to an instance of the outer class, companion object is not.
  • Access: inner object can only be accessed through an instance of the outer class, companion object - directly via the class name.
  • State: inner object can have state specific to the instance, companion object - common to the entire class.
  • Usage: inner object is often used for implementing the State pattern or grouping related objects within an instance. companion object is used for factory methods, constants, or static members of the class.

Example:

class Outer {
    private var outerValue: Int = 0

    inner object InnerObject {
        fun accessOuterValue(): Int {
            return outerValue // inner object has access to outer class members
        }
    }

    companion object CompanionObject {
        const val CONSTANT = "Some constant"

        fun createOuter(): Outer {
            return Outer() // factory method
        }
    }
}

fun main() {
    val outer = Outer.CompanionObject.createOuter() // access to companion object
    // val inner = Outer.InnerObject // Error: cannot access InnerObject without an instance of Outer
    val inner = outer.InnerObject // access to inner object via an instance

    println(inner.accessOuterValue())
    println(Outer.CompanionObject.CONSTANT)
    println(Outer.CONSTANT) // syntactic sugar for accessing members of CompanionObject
}