Home » Android » How to use null with kotlin @Parcelize

How to use null with kotlin @Parcelize

Posted by: admin November 1, 2017 Leave a comment


Here is very simple code:

data class Inner(val a: Int): Parcelable

data class Test(val a: Int, val inner: Inner?): Parcelable

class ExampleInstrumentedTest {
    fun testParcel() {
        val test = Test(0, null)

        val parcel = Parcel.obtain()
        parcel.writeParcelable(test, test.describeContents())

I have nullable property Test.inner. If it is not null, the code works fine but when it is null then I have the exception:

java.lang.NullPointerException: Attempt to invoke interface method 'void android.os.Parcelable.writeToParcel(android.os.Parcel, int)' on a null object reference

How to resolve this? Maybe I do something wrong.