Skip to content

Instantly share code, notes, and snippets.

@cbeyls
Last active Oct 8, 2021
Embed
What would you like to do?
Kotlin Parcelize extensions
package be.digitalia.sample
import android.os.Parcel
import kotlinx.parcelize.Parceler
import java.math.BigDecimal
import java.math.BigInteger
import java.util.Date
inline fun <T> Parcel.readNullable(reader: () -> T) =
if (readInt() != 0) reader() else null
inline fun <T> Parcel.writeNullable(value: T?, writer: T.() -> Unit) {
if (value != null) {
writeInt(1)
value.writer()
} else {
writeInt(0)
}
}
object DateParceler : Parceler<Date?> {
override fun create(parcel: Parcel) = parcel.readNullable { Date(parcel.readLong()) }
override fun Date?.write(parcel: Parcel, flags: Int) = parcel.writeNullable(this) { parcel.writeLong(time) }
}
object BigIntegerParceler : Parceler<BigInteger?> {
override fun create(parcel: Parcel) = parcel.readNullable { BigInteger(parcel.createByteArray()) }
override fun BigInteger?.write(parcel: Parcel, flags: Int) = parcel.writeNullable(this) {
parcel.writeByteArray(toByteArray())
}
}
object BigDecimalParceler : Parceler<BigDecimal?> {
override fun create(parcel: Parcel) =
parcel.readNullable { BigDecimal(BigInteger(parcel.createByteArray()), parcel.readInt()) }
override fun BigDecimal?.write(parcel: Parcel, flags: Int) = parcel.writeNullable(this) {
parcel.writeByteArray(unscaledValue().toByteArray())
parcel.writeInt(scale())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment