Bird
Raised Fist0
Kotlinprogramming~10 mins

Companion objects as static alternatives in Kotlin - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Companion objects as static alternatives
Define class
↓
Add companion object
↓
Declare static-like members inside companion
↓
Access members via class name
↓
Use members without creating instance
↓
End
Shows how companion objects hold static-like members inside a class, accessible without creating instances.
Execution Sample
Kotlin
class MyClass {
    companion object {
        fun greet() = "Hello from companion"
    }
}

fun main() {
    println(MyClass.greet())
}
Defines a companion object with a function and calls it using the class name without creating an instance.
Execution Table
StepActionEvaluationResult
1Define class MyClass with companion objectClass and companion object createdMyClass and companion object exist
2Define function greet inside companionFunction greet() readygreet() returns "Hello from companion"
3Call MyClass.greet() in mainInvoke greet()Returns "Hello from companion"
4Print result of MyClass.greet()Output to consoleHello from companion
5Program endsNo more codeExecution stops
💡 Program ends after printing the companion object's function result
Variable Tracker
VariableStartAfter Step 2After Step 3Final
MyClassNot definedDefined with companionDefined with companionDefined with companion
companion objectNot definedDefined with greet()Defined with greet()Defined with greet()
greet()Not definedDefinedCalledDefined
Key Moments - 2 Insights
Why can we call greet() without creating an instance of MyClass?
Because greet() is inside the companion object, which acts like a static member accessible via the class name, as shown in execution_table step 3.
Is the companion object itself an instance?
Yes, the companion object is a singleton instance created with the class, but Kotlin lets you access its members like static members, as seen in step 1 and 2.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is printed at step 4?
A"Hello from instance"
B"Hello from companion"
C"greet() called"
DNothing is printed
💡 Hint
Check the 'Result' column at step 4 in execution_table
At which step is the greet() function called?
AStep 1
BStep 2
CStep 3
DStep 5
💡 Hint
Look at the 'Action' column for when greet() is invoked in execution_table
If greet() was defined outside the companion object, how would you call it?
ACreate an instance then call instance.greet()
BYou cannot call it at all
CMyClass.greet()
DCall greet() directly without class or instance
💡 Hint
Remember companion object allows static-like calls; without it, you need an instance (see concept_flow)
Concept Snapshot
class MyClass {
    companion object {
        fun greet() = "Hello"
    }
}

Use MyClass.greet() to call without instance.
Companion objects hold static-like members inside classes.
Full Transcript
This example shows how Kotlin uses companion objects as static alternatives. First, the class MyClass is defined with a companion object. Inside the companion object, a function greet() is declared. This function can be called using the class name directly, without creating an instance of MyClass. The execution steps show defining the class and companion, calling greet(), and printing its result. Variables track the existence of the class, companion object, and greet function. Key moments clarify why greet() can be called without an instance and that the companion object is a singleton instance. The quiz tests understanding of output, function call timing, and calling functions outside companion objects.

Practice

(1/5)
1. What is the main purpose of a companion object in a Kotlin class?
easy
A. To hold static-like members accessible without creating an instance
B. To create multiple instances of a class
C. To inherit properties from another class
D. To define instance variables for each object

Solution

  1. Step 1: Understand companion object role

    Companion objects allow defining members that belong to the class itself, not to instances.
  2. Step 2: Compare with instance members

    Instance variables belong to objects, but companion object members behave like static members accessible via the class name.
  3. Final Answer:

    To hold static-like members accessible without creating an instance -> Option A
  4. Quick Check:

    Companion object = static-like members [OK]
Hint: Companion objects act like static members in Kotlin classes [OK]
Common Mistakes:
  • Thinking companion objects create instances
  • Confusing companion objects with inheritance
  • Assuming companion objects hold instance variables
2. Which of the following is the correct syntax to declare a companion object inside a Kotlin class?
easy
A. object companion { val x = 10 }
B. companion object { val x = 10 }
C. static object { val x = 10 }
D. class companion { val x = 10 }

Solution

  1. Step 1: Recall Kotlin companion object syntax

    The correct keyword order is companion object inside the class.
  2. Step 2: Check each option

    companion object { val x = 10 } uses the correct syntax. Options A, B, and D use incorrect keywords or order.
  3. Final Answer:

    companion object { val x = 10 } -> Option B
  4. Quick Check:

    companion object syntax = companion object { val x = 10 } [OK]
Hint: Remember: 'companion object' keyword order is fixed [OK]
Common Mistakes:
  • Using 'static' keyword which Kotlin does not have
  • Swapping 'object' and 'companion' keywords
  • Declaring companion as a class
3. What will be the output of the following Kotlin code?
class MyClass {
    companion object {
        val number = 42
        fun greet() = "Hello"
    }
}

fun main() {
    println(MyClass.number)
    println(MyClass.greet())
}
medium
A. null\nnull
B. number\ngreet
C. Compilation error
D. 42\nHello

Solution

  1. Step 1: Understand companion object access

    Members inside companion object can be accessed using the class name without creating an instance.
  2. Step 2: Evaluate the print statements

    Printing MyClass.number outputs 42, and MyClass.greet() outputs "Hello".
  3. Final Answer:

    42\nHello -> Option D
  4. Quick Check:

    Companion members accessed via class name = 42 and Hello [OK]
Hint: Access companion members with ClassName.member [OK]
Common Mistakes:
  • Trying to create an instance to access companion members
  • Expecting compilation error due to missing instance
  • Confusing companion members with instance members
4. Identify the error in the following Kotlin code using companion objects:
class Example {
    companion object {
        fun show() = println("Show called")
    }
}

fun main() {
    val e = Example()
    e.show()
}
medium
A. Function show() must return a value
B. Missing companion object keyword
C. Cannot call companion object function on instance
D. Class Example cannot have companion objects

Solution

  1. Step 1: Analyze how companion functions are accessed

    Functions inside companion objects are accessed via the class name, not instances.
  2. Step 2: Check the call e.show()

    Calling show() on instance e causes an error because show() is not an instance method.
  3. Final Answer:

    Cannot call companion object function on instance -> Option C
  4. Quick Check:

    Companion functions accessed via class, not instance [OK]
Hint: Call companion functions with ClassName.function(), not instance [OK]
Common Mistakes:
  • Calling companion functions on instances
  • Forgetting companion object keyword
  • Expecting companion functions to be instance methods
5. You want to create a Kotlin class Calculator with a companion object that provides a static method add to add two integers. Which code snippet correctly implements this and allows calling Calculator.add(5, 3) without creating an instance?
hard
A. class Calculator { companion object { fun add(a: Int, b: Int) = a + b } }
B. class Calculator { fun add(a: Int, b: Int) = a + b }
C. object Calculator { fun add(a: Int, b: Int) = a + b }
D. class Calculator { static fun add(a: Int, b: Int) = a + b }

Solution

  1. Step 1: Identify correct static-like method declaration

    In Kotlin, static methods are created inside companion objects.
  2. Step 2: Evaluate each option

    class Calculator { companion object { fun add(a: Int, b: Int) = a + b } } correctly defines add inside a companion object. class Calculator { fun add(a: Int, b: Int) = a + b } defines an instance method, so requires an object. object Calculator { fun add(a: Int, b: Int) = a + b } uses an object declaration, which works but is not a companion object inside a class. class Calculator { static fun add(a: Int, b: Int) = a + b } uses 'static' keyword which Kotlin does not support.
  3. Final Answer:

    class Calculator { companion object { fun add(a: Int, b: Int) = a + b } } -> Option A
  4. Quick Check:

    Companion object method = class Calculator { companion object { fun add(a: Int, b: Int) = a + b } } [OK]
Hint: Use companion object for static methods inside classes [OK]
Common Mistakes:
  • Using 'static' keyword which Kotlin lacks
  • Defining method outside companion object
  • Using object declaration instead of companion object
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard