Using Companion Objects as Static Alternatives in Kotlin
📖 Scenario: Imagine you are creating a simple app that needs to count how many times a certain action happens. You want to keep this count shared across all instances of a class without creating separate copies for each object.
🎯 Goal: You will build a Kotlin class with a companion object that holds a shared counter. You will then write code to increase and display this counter, demonstrating how companion objects act like static members.
📋 What You'll Learn
Create a Kotlin class named ActionCounter
Inside ActionCounter, create a companion object with a variable count initialized to 0
Add a function increment() inside the companion object to increase count by 1
Add a function getCount() inside the companion object to return the current count
Call increment() three times and then print the current count using getCount()
💡 Why This Matters
🌍 Real World
Companion objects let you keep shared data or helper functions inside a class, similar to static members in other languages. This is useful for counters, constants, or factory methods.
💼 Career
Understanding companion objects is important for Kotlin developers to write clean, efficient code that shares data and behavior without unnecessary object creation.
Progress0 / 4 steps
1
Create the Kotlin class with a companion object and count variable
Create a Kotlin class called ActionCounter. Inside it, create a companion object with a variable count initialized to 0.
Kotlin
Hint
Use var count = 0 inside the companion object to hold the shared count.
2
Add increment and getCount functions inside the companion object
Inside the companion object of ActionCounter, add a function increment() that increases count by 1, and a function getCount() that returns the current value of count.
Kotlin
Hint
Define increment() to add 1 to count. Define getCount() to return count.
3
Call increment three times using the companion object
Call ActionCounter.increment() three times to increase the shared count.
Kotlin
Hint
Call ActionCounter.increment() exactly three times in main().
4
Print the current count using getCount
Add a println statement to print the current count by calling ActionCounter.getCount().
Kotlin
Hint
Use println(ActionCounter.getCount()) to show the count.
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
Step 1: Understand companion object role
Companion objects allow defining members that belong to the class itself, not to instances.
Step 2: Compare with instance members
Instance variables belong to objects, but companion object members behave like static members accessible via the class name.
Final Answer:
To hold static-like members accessible without creating an instance -> Option A
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
Step 1: Recall Kotlin companion object syntax
The correct keyword order is companion object inside the class.
Step 2: Check each option
companion object { val x = 10 } uses the correct syntax. Options A, B, and D use incorrect keywords or order.
Final Answer:
companion object { val x = 10 } -> Option B
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
Step 1: Understand companion object access
Members inside companion object can be accessed using the class name without creating an instance.
Step 2: Evaluate the print statements
Printing MyClass.number outputs 42, and MyClass.greet() outputs "Hello".
Final Answer:
42\nHello -> Option D
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
Step 1: Analyze how companion functions are accessed
Functions inside companion objects are accessed via the class name, not instances.
Step 2: Check the call e.show()
Calling show() on instance e causes an error because show() is not an instance method.
Final Answer:
Cannot call companion object function on instance -> Option C
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
}
In Kotlin, static methods are created inside companion objects.
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.
Final Answer:
class Calculator {
companion object {
fun add(a: Int, b: Int) = a + b
}
} -> Option A
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 unknownstrongwhile earning +1 Grip toward your certificate.