English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this article, you will learn how to create and use companion objects in Kotlin programs with the help of examples.
Before discussing companion objects, let's take an example to access the members of the class.
class Person { fun callMe() = println("I'm called.") {} fun main(args: Array<String>) { val p1 = Person() //Using object p1Call the callMe() method p1.callMe() {}
Here, we created an object p of the Person class1 to call the callMe() method.
However, in Kotlin, you can also call the callMe() method by using the class name (i.e., Person in this example). To do this, you need to mark the companion keywordObject declarationObject declaration to create a companion object.
class Person { companion object Test { fun callMe() = println("I'm called.") {} {} fun main(args: Array<String>) { Person.callMe() {}
When the program is run, the output is:
I'm called.
In the program, the Test object is declared using the companion keyword to create a companion object. Therefore, you can call the method callMe() by using the following class name:
Person.callMe()
The name of the companion object is optional and can be omitted.
class Person { //The name of the companion object is optional and can be omitted. companion object { fun callMe() = println("I'm called.") {} {} fun main(args: Array<String>) { Person.callMe() {}
If you are familiar with Java, you may associate companion objects with static methods (even though they work internally in a completely different way)
Companion objects can access the private members of the class. Therefore, they can be used to implement the factory method pattern.