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?
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.
I can suggest two solutions to this problem:
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)..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)..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.
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