Kotlin Companion Objects

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.

Output: The output of this code will be like below image.

Campnion!

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.

It is not compulsary to use Object Name (i.e. Test in above example), It is optional and can be omitted. Check below code.

Output: It will be same like above image, still you can see below image.

Campnion2

In this tutorial we have learn about the Kotlin Companion Objects and its application with practical example. I hope you will like this tutorial.