Write in parcer nullable value in kotlin

This largely depends on what is the semantics of null as a value of your nullable property. It can mean:

  • If value is null then it is absent and should not be written at all:

    value?.let { writeInt(it) }
    

    Of course, the Parcel receiver should be able to determine if it should read the value or not, this should be clear from the values written earlier.

  • value is provided by some code, and it is an error if it is null at the point where it should be written:

    check(value != null) { "value should be not null at the point it's wriiten" }
    writeInt(value!!)
    

    Also, in this case, consider using lateinit var instead of nullable property.

  • Some default value should be used instead of value:

    writeInt(value ?: someDefaultValue())
    

    With Parcel, this does make sense, because otherwise, if the value is missing, you have to specify the fact somewhere else.

  • ... (null can actually mean many things)

Also, this answer shows many idiomatic ways of dealing with nullable values, and you might find some of them useful.


Resolved by:

source.readValue(Int::class.java.classLoader) as Int?,
dest.writeValue(value)