Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin: Multiple named companion objects

Tags:

kotlin

I have a class which impliments both the java.io.Serializable and android.os.Parcelable. These classes require companion objects of:

companion object CREATOR : Parcelable.Creator<MyClass> {
    override fun createFromParcel(parcel: Parcel): MyClass
    ...
}

and

companion object {
    private val serialVersionUid: Long = 123
}

The trouble is that I can't have both these companion objects because that causes a only one companion object per class exception.

How can I have two companion objects with different names in the same class?

like image 896
mdsimmo Avatar asked Nov 06 '19 08:11

mdsimmo


3 Answers

May be you misunderstood Java examples.

public static Parcelable.Creator<SDFileDir> CREATOR = ...;
public static long serialVersionUid = 123;

In Java - yes, it is separated static object. You can place any count of static fields in class.

In Kotlin there should be only one static object (it is called Companion here). But it is like one more class here. So all new static fields should be inside of it.

companion object {
    @JvmField
    val CREATOR: Parcelable.Creator<SDFileDir> = ...
    val serialVersionUid: Long = 123
}

There is one more thing: annotation @JvmField to work with Java correctly.

like image 98
Ircover Avatar answered Oct 17 '22 09:10

Ircover


I can suggest two solutions to this problem:

  1. As @Ircover said - You can declare the CREATOR (which is simply a static field in Java) inside your companion object alongside your constants, but you'll need to mark in with @JvmField annotation to work as inteded (as it is called from Java)..
  2. You do not necessarily need the companion object for the constant value, it (it won't work with serialVersionUid in your case, as it MUST be inside the class for Java serialization to work) can be moved to a separate object, to a companion object of another class or even inside any .kt file body (outside the class)..
like image 20
Sergei Emelianov Avatar answered Oct 17 '22 09:10

Sergei Emelianov


In fact, companion object in kotlin doesn't correspond to static object in Java, they merely share similar funtionality.

In Java, there are only two concepts involved: the class and its static object.

In Koltin, we are dealing with three concepts: the class, the companion object, and the property of the companion object.

The way we access the property of the companion object is the same as accessing the static object in Java, but in Kotlin, there is an extra layer between the class and the inner property, that is the companion object.

In your case, you are not demanding two companion objects, but two properties of one companion object, so just place these two properties in one companion object.

like image 1
Charles Overflow Avatar answered Oct 17 '22 08:10

Charles Overflow