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

thalesmello picture thalesmello · Nov 5, 2015 · Viewed 52.4k times · Source

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)?

Answer

Dhaval Jivani picture Dhaval Jivani · Aug 15, 2017

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
    }
}