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

Questions:

Here is very simple code:

@Parcelize
data class Inner(val a: Int): Parcelable

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

@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
    @Test
    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.

Answers: