Updated March 30, 2023
Introduction to Kotlin companion object
The kotlin companion object is one of the keywords, and it is used to implement the class, which needs to be the object that is common or access through the entire package with the help of the instance of that class when compared to the java or C# or any other programming languages contains the static keyword and its functions like that kotlin do not have the static and its functions so instead of that companion object its name as similar to the kotlin class name also companion object and its class can access each other private members without new keyword we can able to create the instance of the class.
Syntax
In kotlin language has default keywords, variables, and methods for implementing the application. We can overcome and alternate methods to utilize and satisfy the user needs like the static concept in java to overcome this feature in kotlin language with the help of a companion object.
class name
{
companion object {
fun name()
{
---some logic codes depend upon the requirement---
}
}
}
The above codes are the basic syntax for utilizing and create the object by using the kotlin companion object.
How do companion objects work in Kotlin?
The companion object is the alternate and one of the ways to create the object and utilize it anywhere in the packages. We can access private members of the class by using the companion object. It has an object keyword that combines both declaring class and also it will create the instance of the class. It looks and will define the concept called singleton class, so the single object plays a vital role throughout the application packages. And even though it defines the nested class feature for that can behold members, it is related to the outer areas for the classes. When we call and use the instance in the outer side of the class in the kotlin language will implement and use the object keyword in the workflow. Whenever we use the object keyword, it also creates the anonymous class object that is called an anonymous object. That can be achieved if we want to create the object of the slight modification or some class or interface without declaring that the child or subclass is used. In kotlin, the companion object also follows the design patterns like the factory method more similar to the java language.
Examples
Different examples are mentioned below:
Example #1
Code:
package one;
fun main(args: Array<String>) {
var y = First.vars
First.vars = "Your companion object is called and used on this variable"
First.demos()
val x = second()
x.exam()
}
class First {
companion object Singleton
{
init {
println("Welcome To My Domain it’s a first example related to the kotlin companion object")
}
var vars = "Please enter your first input strings"
fun demos()
{
println(vars)
}
}
init {
println("This method is going to be start the task")
}
}
class second {
fun exam() = println("Have a nice day users please keep on continue to spent the tie with our application")
}
Output:
In the above example, we implement the kotlin application with the help of a companion object and singleton concept.
Example #2
Code:
package one;
class Second {
var stdid:Int = 0
var stdName:String="sivaraman"
var stdRollno:Int=10
var stdAddress:String="Flat 12C, Aravind Enclave, Sathyamoorthy street, Srinivasa nagar, chengalpattu district, chennai-600009"
fun stddets(){
println("Welcome To My Domain this is the second example regarding the kotlin companion object")
println("${this.stdid}")
println("${this.stdName}")
println("${this.stdRollno}")
println("${this.stdAddress}")
println("We have entered the student details like student id, student name, student roll number, student Address etc the information’s are encrypted and it is stored in the separate database in cloud applications")
}
companion object Test{
var x: Int = 3
var empid:Int = 0
var empName:String="sivaraman"
var empSalary:Int=10000
var empAddress:String="Flat 12C, Sathya Enclave, Sathyamoorthy Nagar, Muthamizh Theru, chengalpattu district, chennai-600010"
fun details(){
println("Your details are: $x")
x++
}
fun empdetails(){
println("Welcome To My Domain this is the second example regarding the kotlin companion object")
println("${this.empid}")
println("${this.empName}")
println("${this.empSalary}")
println("${this.empAddress}")
println("We have entered the student details like employee id, employee name, employee salary, employee Address etc. the information’s are encrypted and it is stored in the separate database in cloud applications")
}
}
}
fun main() {
Second.details()
Second.Test.details()
Second.Test.empdetails()
println("Thank you users for spending the time with the companion object application")
}
Output:
In the second example, we used companion objects in the different concepts like student and employee details. We retrieved and called the methods by using the companion object name. It will fetch the datas of whatever we created.
Example #3
Code:
package one;
interface thirdInt {
val test: Int
fun eg() : String
fun dem() {
println("Welcome To My Domain its the third example that related to the kotlin compnion object")
}
}
class thirdInts : thirdInt {
override val test: Int = 12
override fun eg() = "Have a Nice day users"
}
interface infthird {
fun eg1() {
println("We created second interface infthird")
}
}
interface infythirds {
fun eg2() {
println("We created third interface infythirds")
}
}
class thirdclass: infthird, infythirds
class third{
companion object demos{
var p: Int = 3
var empid:Int = 1
var empName:String="Arun"
var empSalary:Int=12000
var empAddress:String="5C, Sathya Enclave, Sathyamoorthy Nagar, Senthamizh Theru, chengalpattu district, chennai-600011"
fun details(){
println("Your details are: $p")
p++
}
}
}
fun main(args: Array<String>) {
val vars = thirdInts()
println("The third example related to the kotlin companion object= ${vars.test}")
print("Thank you for spenting the time: ")
vars.dem()
print("Keep on utilising and spenting the time to our application: ")
println(vars.eg())
val vars1 = thirdclass()
vars1.eg1()
vars1.eg2()
third.demos.details()
}
Output:
In the final example, we used the interface and class in the code, and we used a companion object to create the object for the specific class.
Conclusion
The companion object in kotlin is one of the extra layers that can be used in object creation, like the static concept in other languages like java, etc. When we use the companion object, it is used to takes a further level to allow the code with redundancy and an easy way to maintain and work accordingly.
Recommended Articles
This is a guide to Kotlin companion object. Here we discuss the introduction, syntax, and working of companion objects in Kotlin along with different examples and code implementation. You may also have a look at the following articles to learn more –