AndroidPub
Published in

AndroidPub

Kotlin-Series — Object Declaration & Companion Objects in Kotlin

Usage of Object Declaration & Companion Objects

This Story is from the Kotlin- Series, In which we will learn What is Object Declaration & Companion Objects with the help of an example.

Before going directly towards Companion Objects, Let’s take an example Let’s say I have a class in java name as “MainActivity.java” In which I need to set some constants values so for constants values I created another class in java name as “AppConstants” and initialized the value, Now to access the value I just called with the class name like “AppConstants. MINIMUM_NUMBER”. You can see the below code.

Visit my website at https://danishamjad.com/

That’s how things go in Java, But in Kotlin If you want to access the value, For that, you need to create a companion object by marking object declaration with the keyword companion.

Object :

An Object declaration inside a class is marked with the companion object.

In the above code, we have the object name “AppConstant” and we have the static value name as “NUMBER”, now to access the value we need to call by an object name like this: AppConstant.NUMBER

Companion Object:

Companion Object is initialized when the corresponding class is loaded.

In the above code, we have the class name “AppConstants” and we have the static value name as “NUMBER”, within the companion object, now to access the value we need to call by the class name like this: AppConstants.NUMBER

For Companion object, we don’t need to define the companion object name.

One more important thing about companion object is they can access the private members of the class.

Note:

You can relate companion objects with static methods even though their working is totally different internally.

Sharing the knowledge is Caring :-)

Thanks for reading this article. Be sure to clap to recommend this article if you found it helpful. It means a lot to me.

If you need any help then Join me on Twitter, Linkedin, Github, and Subscribe to my Youtube Channel.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store