Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

How to access companion object context in kotlin?


Asked by Axel Pollard on Dec 06, 2021 FAQ



I have a companion object inside an abstract class and I want to access context to read Shared Preferences, but I'm not able to get the context.
One may also ask,
Kotlin recommends to simply use package-level functions instead. If you need to write a function that can be called without having a class instance but needs access to the internals of a class, you can write it as a member of a companion object declaration inside that class.
In addition, You may encounter a problem where you cannot access the Companion object's method in Java if the new keyword is used in the method call. The new keyword should be omitted. The documentation states: Companion objects and their members can only be accessed via the containing class name, not via instances of the containing class.
In respect to this,
The answer is yes, but the approach is different. There is nothing called static in Kotlin. So, in Kotlin, we use a companion object. Let’s see how can we achieve this.
Keeping this in consideration,
You can learn a lot about this difference by looking at the equivalent Java code. Lucky for you, Android Studio has a way for you to do this. Go to Tools ▸ Kotlin ▸ Show Kotlin Bytecode and click the Decompile button at the top of the Kotlin Bytecode window. You’ll see something like the following: The Java class has a private constructor.