I have a data object, User. One of the properties of User is a Boolean. I can't figure out how to store this Boolean as there is no such writeBoolean() provided out of the box.
From what I've searched online, one way of storing the Boolean property is to use the writeInt() method and a ternary operator.
So I tried it here:
data class User(val contactNumber: String,
val email: String,
val fullName: String,
val isAdmin: Boolean,
val organization: String,
val unitNumber: String) : Parcelable {
override fun writeToParcel(dest: Parcel?, flags: Int) {
dest?.writeString(contactNumber)
dest?.writeString(email)
dest?.writeString(fullName)
dest?.writeInt(isAdmin ? 1 : 0)
dest?.writeString(organization)
dest?.writeString(unitNumber)
}
}
But this syntax seems to only work with Java and not in Kotlin. I'm getting a compiler error indicating Unexpected tokens (use ':' to separate expressions on the same line. How do I accomplish this in Kotlin?
The ternary operator is not supported in kotlin Use if-else instead
writeInt(if(isAdmin) 1 else 0)
Im using writeValue instead, it also usefull for nullable variables
dest.writeValue(this.booleanVar)
booleanVar = parcel.readValue(Boolean::class.java.classLoader) as? Boolean?
if it could be nullable and if not add ?: false
upd: as pointed in other answers dest variable cannot be null. afaik it marked as nullable after code converting using Android Studio. If you use that feature better to double check your code because of convertation could work not properly sometimes.
About ?. in general. You can rewrite it with let operator
dest?.let { it ->
it.write(....)
or even better
dest ?: retrun
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With