Skip to content

Instantly share code, notes, and snippets.

@mcxiaoke
Forked from juanchosaravia/KotlinParcelable
Created January 28, 2016 02:57
Show Gist options
  • Select an option

  • Save mcxiaoke/f6eb2eb8049d1cfc352a to your computer and use it in GitHub Desktop.

Select an option

Save mcxiaoke/f6eb2eb8049d1cfc352a to your computer and use it in GitHub Desktop.
How to use Parcelable in Kotlin v1.0.0-beta-4589
// Inline function to create Parcel Creator
inline fun <reified T : Parcelable> createParcel(crossinline createFromParcel: (Parcel) -> T?): Parcelable.Creator<T> =
object : Parcelable.Creator<T> {
override fun createFromParcel(source: Parcel): T? = createFromParcel(source)
override fun newArray(size: Int): Array<out T?> = arrayOfNulls(size)
}
// custom readParcelable to avoid reflection
fun <T : Parcelable> Parcel.readParcelable(creator: Parcelable.Creator<T>): T? {
if (readString() != null) return creator.createFromParcel(this) else return null
}
// EXAMPLE with custom classes
data class User(
var _id: String? = null,
var email: String? = null,
var name: Name? = null,
var phone: String? = null,
var additional: Additional? = null
) : Parcelable {
protected constructor(parcelIn: Parcel) : this() {
this._id = parcelIn.readString()
this.email = parcelIn.readString()
this.name = parcelIn.readParcelable(Name.CREATOR)
this.phone = parcelIn.readString()
this.additional = parcelIn.readParcelable(Additional.CREATOR)
}
override fun describeContents(): Int {
return 0
}
override fun writeToParcel(dest: Parcel, flags: Int) {
dest.writeString(_id)
dest.writeString(email)
dest.writeParcelable(name, 0)
dest.writeString(phone)
dest.writeParcelable(additional, 0)
}
companion object {
val CREATOR = createParcel { User(it) }
}
}
data class Name(
var first: String? = null,
var last: String? = null
) : Parcelable {
protected constructor(parcelIn: Parcel) : this() {
this.first = parcelIn.readString()
this.last = parcelIn.readString()
}
override fun describeContents(): Int {
return 0
}
override fun writeToParcel(dest: Parcel, flags: Int) {
dest.writeString(first)
dest.writeString(last)
}
companion object {
val CREATOR = createParcel { Name(it) }
}
}
data class Additional(
var licensePlate: String? = null
) : Parcelable {
protected constructor(parcelIn: Parcel) : this() {
this.licensePlate = parcelIn.readString()
}
override fun writeToParcel(dest: Parcel, flags: Int) {
dest.writeString(this.licensePlate)
}
override fun describeContents(): Int {
return 0
}
companion object {
val CREATOR = createParcel { Additional(it) }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment