In this tutorial you will learn about the Kotlin Companion Objects and its application with practical example.
Kotlin Companion Objects
In kotlin we can call method using class name, for that we need to create a companion object through object declaration with companion keyword.
Let’s understand it by example, we will create two example, in first one we will call method without Companion Object and in second example we will use Companion Object.
Example:Without Companion Object: In this example we are not using Companion Object.
1 2 3 4 5 6 7 8 9 10 |
class CampanionDemo { fun printMe() = println("W3Adda : I'm printed.") } fun main(args: Array<String>) { val prnt = CampanionDemo() prnt.printMe() } |
Output: The output of this code will be like below image.
Example: With Companion Object: In this example we will use campanion object. You can see in below example that we used object declaration with companion keyword for Test object.
1 2 3 4 5 6 7 8 9 |
class CompanionDemo { companion object Test { fun printMe() = println("W3Adda : I'm printed.") } } fun main(args: Array<String>) { CompanionDemo.printMe(); } |
It is not compulsary to use Object Name (i.e. Test in above example), It is optional and can be omitted. Check below code.
1 2 3 4 5 6 7 8 9 |
class CampanionDemo { companion object{ fun printMe() = println("W3Adda : I'm printed.") } } fun main(args: Array<String>) { CampanionDemo.printMe(); } |
Output: It will be same like above image, still you can see below image.