Is there a convenient way to create Parcelable data classes in Android with Kotlin?

I'm currently using the excellent AutoParcel in my Java project, which facilitates the creation of Parcelable classes.

Now, Kotlin, which I consider for my next project, has this concept of data classes, that automatically generate the equals, hashCode and toString methods.

Is there a convenient way to make a Kotlin data class Parcelable in a convenient way (without implementing the methods manually)?


Solution 1:

Kotlin 1.1.4 is out

Android Extensions plugin now includes an automatic Parcelable implementation generator. Declare the serialized properties in a primary constructor and add a @Parcelize annotation, and writeToParcel()/createFromParcel() methods will be created automatically:

@Parcelize
class User(val firstName: String, val lastName: String) : Parcelable

So you need to enable them adding this to you module's build.gradle:

apply plugin: 'org.jetbrains.kotlin.android.extensions'

android {
    androidExtensions {
        experimental = true
    }
}

Solution 2:

You can try this plugin:

android-parcelable-intellij-plugin-kotlin

It help you generate Android Parcelable boilerplate code for kotlin's data class. And it finally look like this:

data class Model(var test1: Int, var test2: Int): Parcelable {

    constructor(source: Parcel): this(source.readInt(), source.readInt())

    override fun describeContents(): Int {
        return 0
    }

    override fun writeToParcel(dest: Parcel?, flags: Int) {
        dest?.writeInt(this.test1)
        dest?.writeInt(this.test2)
    }

    companion object {
        @JvmField final val CREATOR: Parcelable.Creator<Model> = object : Parcelable.Creator<Model> {
            override fun createFromParcel(source: Parcel): Model{
                return Model(source)
            }

            override fun newArray(size: Int): Array<Model?> {
                return arrayOfNulls(size)
            }
        }
    }
}

Solution 3:

Just click on the data keyword of your kotlin data class, then press alt+Enter, select the first option saying "Add Parceable Implementation"