Kotlin added parcelable support in version 1.1.4. Here we can kotlin-android-extensions toimplement Parcelable in much simpler way using @Parcelize and Parcelable.
Interface for classes whose instances can be written to and restored from a Parcel
. Classes implementing the Parcelable interface must also have a non-null static field called CREATOR
of a type that implements the Parcelable.Creator
interface.
First step to use parcelize is add extension to build.gradle file
androidExtensions {
experimental = true
}
Must have to declare the serialized properties in a primary constructor and add a @Parcelize annotation, and writeToParcel()/createFromParcel() methods will be created automatically.
Here is the code with Parcelable, which can be used both class or data class.
data class State(val code: String?, val name: String) : Parcelable {
constructor(source: Parcel) : this(
source.readString(),
source.readString()!!
)
override fun describeContents() = 0
override fun writeToParcel(dest: Parcel, flags: Int) = with(dest) {
writeString(code)
writeString(name)
}
companion object {
fun create(name:String) = State(code = null, name = name)
@JvmField
val CREATOR: Parcelable.Creator<State> = object : Parcelable.Creator<State> {
override fun createFromParcel(source: Parcel): State = State(source)
override fun newArray(size: Int): Array<State?> = arrayOfNulls(size)
}
}
}
Which can be simplified using @Parcelize, that is much more robust and removing lots of boilerplate code.
@Parcelize
data class State(
val code: String?,
val name: String
) : Parcelable {
companion object {
fun create(name: String) = State(code = null, name = name)
}
}
Here you can use @Parcelize both data class and class and compainion object is optional, either you can use only if necessary, other wise it looks like even more simpler.
@Parcelize
data class State(
val code: String?,
val name: String
) : Parcelable
You can also use @Parcelize in enum too,
enum class Married {
YES, NO
}
@Parcelize
class Employee(var isMarried: Married) : Parcelable
Thanks and Happy Coding !!!
Curtesy: