Use of Parceler with Kotlin data class with constructor for serialization

Martynas Jurkus picture Martynas Jurkus · Nov 24, 2015 · Viewed 10.3k times · Source

Is there a way to use Parceler with Kotlin data classes and constructor for serialization without using @ParcelProperty annotation for each field?

If I try and use library like this:

@Parcel
data class Valve @ParcelConstructor constructor(val size: Int)

I get Error:Parceler: No corresponding property found for constructor parameter arg0. But if I add @ParcelProperty("size") it works just fine.
Why is that?

Update:
There are other another way to use this library.
I could just remove @ParcelConstructor annotation, but then I will get error
Error:Parceler: No @ParcelConstructor annotated constructor and no default empty bean constructor found.
I think (haven't tested it) I also could make all constructor parameters optional and add @JvmOverloads but that has a side effect that I have to check all properties of the class if they are null or not.

Update 2:
This is what worked for me:

@Parcel
data class Valve(val size: Int? = null)

In short generated Java class must have default empty constructor. One way to achieve that is to do as above - all variables should have default values.

Answer

voddan picture voddan · Nov 24, 2015

According to the docs, Parceler by default works with public fields. But a usual Kotlin data class (as in your example) is rather a "traditional getter/setter bean", since every Kotlin property is represented by a private field and a getter/[setter].

TL; DR: I think this will work:

@Parcel(Serialization.BEAN)
data class Valve(val size: Int = 10)

Note the default value, it allows Kotlin to automatically generate an additional empty constructor, which is required by the Java Been specification.

Another way would be to mark the constructor that we already have:

@Parcel(Serialization.BEAN)
data class Driver @ParcelConstructor constructor(val name: String)

The specific document: https://github.com/johncarl81/parceler#gettersetter-serialization