0

I am having trouble in understanding the way @Parcelize working in Kotlin. According to documentations

only the primary constructor properties will be serialized.

But when I serialize and deserialize classes with empty primary contractors, it is still serializing and deserializing all the fields. For example, below class

@Parcelize
class Node(): Parcelable {
    var field: String? = null
}

As primary contractor doesn't have any field, according to documentations I should have field = null always after ser/des. But whenever I run below codes

val before = Node()
before.field = "someField"

val bundle = Bundle().apply{ putParcelable("someKey", before) }
val after = bundle.getParcelable<Node>("someKey")

field is successfully serialized and deserialized and will have value of someField. Am I missing something or did Parcelize got updated but they didn't update documentation?

By the way if I leave Node declaration as above, Android Studio gives me warning that field will not be serialized into Parcel. But it is.

musooff
  • 6,412
  • 3
  • 36
  • 65

1 Answers1

0

You should define it in the constructor itself and it will work just fine.

@Parcelize
class Node( var field: String? = null) : Parcelable

And to use empty constructors in kotlin you can add this in app gradle file.

apply plugin: 'kotlin-noarg'

With this you can use classes with empty constructors.

I hope this helps.

Sarthak Gandhi
  • 2,130
  • 1
  • 16
  • 23
  • Thanks for the feedback, but I know it works. My question is even if I don't put fields inside constructor it sill works – musooff Mar 22 '19 at 08:23