What is a Companion Object and why do we need it? - kotlin

I am currently learning the Kotlin language.
I want to know what is a Companion Object, and why do we need it?
I think there is a similar concept in Scala.

Members of the companion object can be called by using simply the class name as the qualifier
like a java static
if called Anothrer class's member variable or method
you use that companion object

Related

How to declare Singleton instance in Kotlin , is it similar to how we declare Singleton class?

In an interview I was told to write a Singleton class so I wrote the following code
object Ant{
}
but later he asked me to write Singleton instance which confused me and I ended up writing like this
object what{
}
now, I know I am wrong but I am really curious how to write down Singleton Instance.
please check my helper class, What I was using might be wrong so please correct me
class Helper{
companion object{
#Volatile
var INSTANCE : Helper? = null
fun getInstance(): Helper {
return INSTANCE?: synchronized(this){
val instance = Helper()
INSTANCE = instance
instance
}
}
}
}
and then I would create a variable like this val helper = Helper.getInstance() and use this object from then on, sometimes I declare them as global variables outside class to make it easier to access across the app
recently we have shifted to Koin so we just declare these classes as singleton by using #Single ksp annotation
It is hard to guess what an interviewer was asking about, after the event, but in your code above there is no instance of either Ant or What yet, only the object declaration. You would need to instantiate the object like:
val mySingleton = What
Object declarations are initialized lazily when first used
I think you were right!
In Kotlin, an object is a singleton: it defines a class, with exactly one instance. (That one instance is created automatically, and you can't create any others.) So if you need a singleton, that's the standard way to get it.
You could do something like:
class Ant private constructor() {
companion object {
val INSTANCE = Ant()
}
}
That's how you'd have to do it in Java: a private constructor and a single static instance. It may be that your interviewer was more familiar with Java, and was expecting you to do that — but that's absolutely pointless in Kotlin, because object does exactly the same, only more concisely (and with less opportunity for errors or race conditions or whatever).
If you were using a framework such as Spring, that provides other ways of creating single instances (e.g. with annotations such as #Component, #Bean, etc.) but those are specific to the framework, so you'd probably know if you needed anything like that.
Or your interviewer may have something else in mind — but in that case, he should have given you some hints; you're not a mind-reader!
The bottom line is that without any further information, object is the most obvious way to get a singleton, so from what you've posted, you were right.

How to get only declared members (not inherited) with Kotlin Reflection?

Is there any way to get only the declared members of a class (not inherited) with Kotlin Reflection?
Something equivalent to getDeclaredMethods(), or ...Fields(), in Java, but for members and JVM free, which:
Returns an array containing Method objects reflecting all the declared methods of the class ... but excluding inherited methods.
Or like a binding flag, such as BindingFlags.DeclaredOnly of dotnet.
Because the reflection is based on the class, So the following is only for the kotlin/JVM, not suitable for the Kotlin/JS or Kotlin/Native.
For the Kotlin/JS it supports limit, for detail, you can see this
document
The only supported parts of the API are: (::class),KType and typeOf
Firstly, you can use the SomeClass::class.java.declaredMethods to get the
getDeclaredMethods. That is the java method. Because the Kotlin file after compiled it is still a class. so you can directly use it.
You can also add the kotlin reflect to get the KClass, then use the declaredFunctions to get. Here is the Document
Returns all functions declared in this class. If this is a Java class, it includes all non-static methods (both extensions and non-extensions) declared in the class and the superclasses, as well as static methods declared in the class
For how to get the KClass, you can use the following code
Class.forName("mypackage.MyClass").kotlin.declaredFunctions
Besides the method, the other property you can also get. such as
declaredMembers
Returns all functions and properties declared in this class. Does
not include members declared in supertypes.
allSuperclasses
functions
Returns all functions declared in this class, including all non-static methods declared in the class and the superclasses, as well as static methods declared in the class.
you can read the document using it.

How to create static functions in Kotlin without creating an object

I want to have functions that sit in classes (not polluting the global namespace) but are accessed statically (never creating an object in which they reside).
Proposed solution:
object A {
#JvmStatic
fun mkdir() {}
}
Is this a good solution or will it inevitably create an object? Which pattern should I use?
Unfortunately, there's currently no way to create a static function on a class in Kotlin that doesn't result in the instantiation of an Object (the companion object). You'll have to write it in Java and call it from Kotlin if you want to do this.
The #JvmStatic annotation creates a static method in the JVM bytecode, but all that does is retrieve the instance of the companion object and call the method on it, which you can verify by decompiling the resulting bytecode.

Where is the Enum::valueOf defined?

When I define an enum class in Kotlin
enum class Answer {
YES,
NO
}
It has a valueOf(value: String) attached to it.
val doYouWantBeerOrCoffee = Answer.valueOf("YES") // Answer.YES
But where is this function actually defined? It is definitely not in the Enum.Kt and using Idea's Go to Implementation tool only takes me back to my Answer enum definition.
It's generated by the compiler. That's what "synthetic" means in
Enum classes in Kotlin have synthetic methods allowing to list the defined enum constants and to get an enum constant by its name.
If you decompile Answer.class you'll see it, but it isn't written as Kotlin (or Java) source code anywhere.
This method is a part of JDK, and defined in Enum.java class.
Which is the common base class of all Java language enumeration types.
Kotlin uses the same class for enums

Find out if an object is a class object rather than an instance of a class

Using the Objective-C runtime library, how do we find out if an object is a class object rather than an instance of a class?
Easiest surefire way I know is class_isMetaClass(object_getClass(yourObject)). (This works because classes are always instances of metaclasses.)