Skip to content Skip to sidebar Skip to footer

Companion Objects In Kotlin Interfaces

I am trying to make a interface Parcelable, as such I need a interface like this interface AB : Parcelable { companion object { val CREATOR : Parcelable.Creator

Solution 1:

In Kotlin, an interface can have a companion object but it is not part of the contract that must be implemented by classes that implement the interface. It is just an object associated to the interface that has one singleton instance. So it is a place you can store things, but doesn't mean anything to the implementation class.

You can however, have an interface that is implemented by a companion object of a class. Maybe you want something more like this:

interfaceBehavior{
   funmakeName(): String
}

dataclassMyData(valdata: String) {
    companionobject: Behavior {  // interface used hereoverridefunmakeName(): String = "Fred"
    }
}

Note that the data class does not implement the interface, but its companion object does.

A companion object on an interface would be useful for storing constants or helper functions related to the interface, such as:

interfaceRedirector{
    funredirectView(newView: String, redirectCode: Int)companionobject {
        val REDIRECT_WITH_FOCUS = 5val REDIRECT_SILENT = 1
    }
}

// which then can be accessed as:val code = Redirector.REDIRECT_WITH_FOCUS

Solution 2:

By convention classes implementing the Parcelable interface must also have a non-null static field called CREATOR of a type that implements the Parcelable.Creator interface.

You need to annotate CREATOR property with @JvmField annotation to expose it as a public static field in containing data class.

Also you can take a look at https://github.com/grandstaish/paperparcel — an annotation processor that automatically generates type-safe Parcelable wrappers for Kotlin and Java.

Post a Comment for "Companion Objects In Kotlin Interfaces"