We decide between companion and top-level functions to organize code clearly and make it easy to use.
0
0
Companion vs top-level functions decision in Kotlin
Introduction
When you want a function related to a class but not needing an object instance.
When you want to group helper functions inside a class for better structure.
When you want simple utility functions that don't belong to any class.
When you want to call functions without creating objects.
When you want to keep code clean and easy to find.
Syntax
Kotlin
class MyClass { companion object { fun companionFunction() { // code here } } } // Top-level function fun topLevelFunction() { // code here }
Companion functions live inside a class's companion object.
Top-level functions are declared outside any class.
Examples
Companion function
add is called using the class name without creating an object.Kotlin
class Calculator { companion object { fun add(a: Int, b: Int) = a + b } } fun main() { println(Calculator.add(3, 4)) }
Top-level function
greet is called directly without any class.Kotlin
fun greet(name: String) { println("Hello, $name!") } fun main() { greet("Alice") }
Sample Program
This program shows using a companion function log inside Logger class and a top-level function printWelcome. Both are called without creating objects.
Kotlin
class Logger { companion object { fun log(message: String) { println("Log: $message") } } } fun printWelcome() { println("Welcome to the program!") } fun main() { Logger.log("Program started") printWelcome() Logger.log("Program ended") }
OutputSuccess
Important Notes
Use companion functions to keep related functions inside a class for better organization.
Use top-level functions for general utilities that don't fit inside a class.
Companion functions can access private members of the class, top-level functions cannot.
Summary
Companion functions belong to a class and are called with the class name.
Top-level functions are independent and called directly.
Choose companion functions to group related code; choose top-level for general helpers.