I'm wondering, why can't a class get an access to a companion object's field?
class MyClass {
println(val1) // not found, why?
}
object MyClass {
val val1 = "str"
}
It should, it should even have an access to the private fields of object MyClass
.
To create a companion object, you need to add the companion keyword in front of the object declaration. The output of the above code is “ You are calling me :) ” This is all about the companion object in Kotlin. Hope you liked the blog and will use the concept of companion in your Android application.
Answer: Companion object is not a Singleton object or Pattern in Kotlin – It's primarily used to define class level variables and methods called static variables. This is common across all instances of the class.
A companion object is an object that's declared in the same file as a class , and has the same name as the class. A companion object and its class can access each other's private members. A companion object's apply method lets you create new instances of a class without using the new keyword.
You can do that by using MyClass.val1
instead of just val1
.
I guest that's done to denote that companion object members can be accessed from anywhere (with default modifiers).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With