Companion Object in Kotlin

Needone App
1 min readDec 6, 2022

--

In Kotlin, a companion object is a special object that is associated with a class. It is similar to a static field in other languages, but it is more powerful and flexible.

A companion object is defined inside a class, using the companion keyword, and it has the same visibility as the class itself. This means that it can be accessed from anywhere within the same package as the class, without the need to create an instance of the class.

A companion object can contain properties and methods, just like a regular object, and it can be used to store shared data or implement utility functions that can be accessed by all instances of the class.

One common use case is that companion object is used to created static variable or method. As there is no static in kotlin.

Example:

We can also ignore the companion object name like this:

Overall, companion objects in Kotlin provide a convenient way to define and access shared data and utility functions associated with a class, similar to the static property and methods in other programming languages.

Originally published at https://needone.app on December 6, 2022.

--

--

No responses yet