mdsimmo
mdsimmo

Reputation: 619

Kotlin: Multiple named companion objects

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?

Upvotes: 9

Views: 4184

Answers (3)

Charles Overflow
Charles Overflow

Reputation: 25

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.

Upvotes: 1

Ircover
Ircover

Reputation: 2446

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.

Upvotes: 13

Sergey Emeliyanov
Sergey Emeliyanov

Reputation: 6961

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)..

Upvotes: 1

Related Questions