Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store boolean property for Parcelable interface?

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?

like image 873
fishhau Avatar asked Apr 06 '26 23:04

fishhau


1 Answers

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
like image 122
Vovchik Avatar answered Apr 13 '26 00:04

Vovchik