Kotlin Introduction
- Kotlin Hello World
- Kotlin Data Types
- Kotlin Operators
- Kotlin Type Conversion
- Kotlin Expression & Statement
- Kotlin Comments
- Kotlin Input/Output
Kotlin Flow Control
- Kotlin if expression
- Kotlin when Expression
- Kotlin while Loop
- Kotlin for Loop
- Kotlin break
- Kotlin continue
Kotlin Functions
Kotlin OOP
- Kotlin Class and Objects
- Kotlin Constructors
- Kotlin Getters and Setters
- Kotlin Inheritance
- Kotlin Visibility Modifiers
- Kotlin Abstract Class
- Kotlin Interfaces
- Kotlin Nested and Inner Classes
- Kotlin Data Class
- Kotlin Sealed Class
- Kotlin Object
- Kotlin Companion Objects
- Kotlin Extension Function
- Kotlin Operator Overloading
In this article, you will learn to create and use companion objects in your Kotlin program with the help of examples.
Before taking about companion objects, let’s take an example to access members of a class.
class Person {
fun callMe() = println("I'm called.")
}
fun main(args: Array<String>) {
val p1 = Person()
// calling callMe() method using object p1
p1.callMe()
}
Here, we created an object p1 of the Person class to call callMe()
method. That’s how things normally work.
However, in Kotlin, you can also call callMe()
method by using the class name, i.e, Person in this case. For that, you need to create a companion object by marking object declaration with companion
keyword.
Example: Companion objects
class Person {
companion object Test {
fun callMe() = println("I'm called.")
}
}
fun main(args: Array<String>) {
Person.callMe()
}
When you run the program, the output will be:
I'm called.
In the program, Test object declaration is marked with keyword companion to create a companion object. Hence, it is possible to call callMe()
method by using the name of the class as:
Person.callMe()
The name of the companion object is optional and can be omitted.
class Person {
// name of the companion object is omitted
companion object {
fun callMe() = println("I'm called.")
}
}
fun main(args: Array<String>) {
Person.callMe()
}
If you are familiar with Java, you may relate companion objects with static methods (even though how they work internally is totally different).
The companion objects can access private members of the class. Hence, they can be used to implement the factory method patterns.