https://kotlinlang.org logo
#android
Title
# android
d

Dr.jacky

02/20/2020, 10:35 AM
Hello everyone! Does
@Parcelize
works on Pair type as well? Or in the other hand, does it work on classes that implement
Serializable
. ? I tried on a sample app and it worked. But I have a crash in Crashlytics:
Fatal Exception: java.lang.RuntimeException
Parcelable encountered IOException writing serializable object (name = kotlin.Pair)
keyboard_arrow_up
🤔 1
f

Federico Piantoni

02/20/2020, 10:52 AM
Pair is Serializable so it works on Serializable classes. What's inside your Pair?
👍 1
d

Dr.jacky

02/20/2020, 10:58 AM
@Federico Piantoni
Pair<String, Int>
Sorry, I didn’t get! you meant so
@Parcelize
works on classes that implementing Serializable? Without
@Serializable
f

Federico Piantoni

02/20/2020, 11:12 AM
Sorry, I did not see the @
d

Dr.jacky

02/20/2020, 11:14 AM
@Federico Piantoni What do you mean!?
f

Federico Piantoni

02/20/2020, 11:23 AM
If you would to create a parcelable Pair class, you can create own implementation of Pair with @Parcelable.
d

Dr.jacky

02/20/2020, 11:26 AM
I did:
Copy code
data class Pair2<out A : Parcelable, out B : Parcelable>(
    val first: A,
    val second: B
) : Parcelable {
    private val ff: A = first
    private val ss: B = second
    constructor(parcel: Parcel) : this(
        parcel.readValue(Parcelable::class.java.classLoader) as A,
        parcel.readValue(Parcelable::class.java.classLoader) as B
    )
    /**
     * Returns string representation of the [Pair] including its [first] and [second] values.
     */
    public override fun toString(): String = "($first, $second)"
    override fun writeToParcel(dest: Parcel, flags: Int) {
        dest.writeValue(ff)
        dest.writeValue(ss)
    }
    override fun describeContents(): Int {
        return 0
    }
    companion object CREATOR : Parcelable.Creator<Pair2<Parcelable, Parcelable>> {
        override fun createFromParcel(parcel: Parcel): Pair2<Parcelable, Parcelable> {
            return Pair2(parcel)
        }
        override fun newArray(size: Int): Array<Pair2<Parcelable, Parcelable>?> {
            return arrayOfNulls(size)
        }
    }
}
The point is as I mentioned in my first message, even without having custom Pair class, it worked on my hello project! Because of that I asked if @Parcelize works on Pair? And asked if @Parcelize works on
: Serializable
classes? Apart from all of them, I saw this too: https://youtrack.jetbrains.com/issue/KT-20742 Which made me to have doubts about the whole idea, and maybe I need to put both annotations over that class that has Pair field.
@sajadgarshasbi Any idea about this?
b

Barco

02/23/2020, 9:01 PM
Serializable
is just an empty interface that indicates to users of this Object that it can be serialized. You can still have runtime errors when trying to serialize it. So I think a Serializable will not always work with
@Parcelize
out of the box :)
317 Views