A companion object lets you create functions or properties tied to a class, not to instances. Implementing interfaces in companion objects helps organize shared behavior or constants in one place.
0
0
Companion object with interfaces in Kotlin
Introduction
When you want to group helper functions related to a class but not to any specific object.
When you want to implement an interface that provides common behavior or constants for a class.
When you want to access interface methods or properties without creating an instance of the class.
When you want to keep related static-like functionality inside the class for better organization.
Syntax
Kotlin
class ClassName { companion object : InterfaceName { override fun interfaceMethod() { // implementation } } } interface InterfaceName { fun interfaceMethod() }
The companion object acts like a static object inside the class.
Implementing an interface in the companion object means you can call interface methods on the class itself.
Examples
The companion object implements Logger interface. We call log() directly on the class.
Kotlin
interface Logger { fun log(message: String) } class MyClass { companion object : Logger { override fun log(message: String) { println("Log: $message") } } } fun main() { MyClass.log("Hello from companion") }
The companion object holds a constant PI by implementing Constants interface.
Kotlin
interface Constants { val PI: Double } class MathUtils { companion object : Constants { override val PI = 3.14159 } } fun main() { println("PI = ${MathUtils.PI}") }
Sample Program
This program shows a companion object implementing the Greeter interface. We call greet() on the class without creating an instance.
Kotlin
interface Greeter { fun greet(name: String) } class Friendly { companion object : Greeter { override fun greet(name: String) { println("Hello, $name! Welcome!") } } } fun main() { Friendly.greet("Alice") }
OutputSuccess
Important Notes
You can only have one companion object per class.
Companion objects can implement multiple interfaces if needed.
Use companion objects to keep related static-like code organized inside the class.
Summary
Companion objects let you create static-like members inside a class.
Implementing interfaces in companion objects helps organize shared behavior.
You can call interface methods on the class itself without creating instances.