2

The compiler is giving me the error Type mismatch: Required: String, Found: String? for the lines parcel.writeString(firstName) and parcel.writeString(lastName) inside the constructor of a Parcelable data class.

Here is my class.

data class Mouse(
val firstName: String,
val lastName: String,
val age: Int ) : Parcelable {
constructor(parcel: Parcel) : this(
    parcel.readString(),
    parcel.readString(),
    parcel.readInt()
)

override fun writeToParcel(parcel: Parcel, flags: Int) {
    parcel.writeString(firstName)
    parcel.writeString(lastName)
    parcel.writeInt(age)
}

override fun describeContents(): Int {
    return 0
}

companion object CREATOR : Parcelable.Creator<Mouse> {
    override fun createFromParcel(parcel: Parcel): Mouse {
        return Mouse(parcel)
    }

    override fun newArray(size: Int): Array<Mouse?> {
        return arrayOfNulls(size)
    }
}}

I don't understand why there is the error and how to correct it.

1 Answer 1

6

Actually, your error is caused by other lines. parcel.readString() returns String?, and you try to pass it to your primary constructor as firstName parameter which has String type. To fix it, you can, for example, pass a default value if returned string is null:

constructor(parcel: Parcel) : this(
    parcel.readString() ?: "",
    parcel.readString() ?: "",
    parcel.readInt()
)
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your answer. I should insert ?:"" even if there are the linesval firstName: String, val lastName: String,?
Yes, because parcel.readString() returns a nullable type String?, and firstName has non-nullable type String, so you have to deal with null values.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.