Skip to content

Instantly share code, notes, and snippets.

@le0nidas
Created March 20, 2022 11:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save le0nidas/80c68199aeeef06ed0d214ccae10cc53 to your computer and use it in GitHub Desktop.
Save le0nidas/80c68199aeeef06ed0d214ccae10cc53 to your computer and use it in GitHub Desktop.
inline fun <reified T : Parcelable> Parcel.readParcelable(): T? {
val exists = readInt() == 1
if (!exists) return null
return parcelableCreator<T>().createFromParcel(this)
}
@Suppress("UNCHECKED_CAST")
inline fun <reified T : Parcelable> parcelableCreator(): Parcelable.Creator<T> =
T::class.java.getDeclaredField("CREATOR").get(null) as? Parcelable.Creator<T>
?: throw IllegalArgumentException("Could not access CREATOR field in class ${T::class.simpleName}")
fun <T : Parcelable> Parcel.writeParcelable(t: T?) {
if (t == null) {
writeInt(0)
} else {
writeInt(1)
t.writeToParcel(this, 0)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment