What if you could call class functions without making objects, keeping your code neat and fast?
Why Companion objects as static alternatives in Kotlin? - Purpose & Use Cases
Imagine you want to create a utility function in Kotlin that belongs to a class but doesn't need an instance to work, like a calculator's add method. Without companion objects, you'd have to create an object every time or place the function outside the class, which feels disconnected.
Manually creating instances just to call utility functions wastes memory and time. Placing functions outside classes breaks the idea of grouping related code, making your program messy and harder to understand.
Companion objects let you put functions and properties inside a class that behave like static members. This means you can call them without creating an instance, keeping your code organized and efficient.
class Calculator { fun add(a: Int, b: Int): Int { return a + b } } val calc = Calculator() val result = calc.add(2, 3)
class Calculator { companion object { fun add(a: Int, b: Int) = a + b } } val result = Calculator.add(2, 3)
You can organize utility functions inside classes and call them directly without creating objects, making your code cleaner and faster.
Think of a Logger class where you want to log messages without creating a Logger instance every time. Companion objects let you call Logger.log("message") directly.
Companion objects provide a way to create static-like members inside classes.
They help avoid unnecessary object creation for utility functions.
They keep related code grouped and easy to find.
Practice
companion object in a Kotlin class?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 AQuick Check:
Companion object = static-like members [OK]
- Thinking companion objects create instances
- Confusing companion objects with inheritance
- Assuming companion objects hold instance variables
Solution
Step 1: Recall Kotlin companion object syntax
The correct keyword order iscompanion objectinside 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 BQuick Check:
companion object syntax = companion object { val x = 10 } [OK]
- Using 'static' keyword which Kotlin does not have
- Swapping 'object' and 'companion' keywords
- Declaring companion as a class
class MyClass {
companion object {
val number = 42
fun greet() = "Hello"
}
}
fun main() {
println(MyClass.number)
println(MyClass.greet())
}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
PrintingMyClass.numberoutputs 42, andMyClass.greet()outputs "Hello".Final Answer:
42\nHello -> Option DQuick Check:
Companion members accessed via class name = 42 and Hello [OK]
- Trying to create an instance to access companion members
- Expecting compilation error due to missing instance
- Confusing companion members with instance members
class Example {
companion object {
fun show() = println("Show called")
}
}
fun main() {
val e = Example()
e.show()
}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
Callinge.show()show()on instanceecauses an error becauseshow()is not an instance method.Final Answer:
Cannot call companion object function on instance -> Option CQuick Check:
Companion functions accessed via class, not instance [OK]
- Calling companion functions on instances
- Forgetting companion object keyword
- Expecting companion functions to be instance methods
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?Solution
Step 1: Identify correct static-like method declaration
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 definesaddinside 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 AQuick Check:
Companion object method = class Calculator { companion object { fun add(a: Int, b: Int) = a + b } } [OK]
- Using 'static' keyword which Kotlin lacks
- Defining method outside companion object
- Using object declaration instead of companion object
Ready to prove it?
Pass the test and this pattern moves unknown
