146
votes

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

15
You mean to use AutoParcel with Kotlin? I thought about that, but if there was a way to have data classes Parcelable built in into the language, it would be beautiful. Specially considering a huge part of Kotlin usage will come from Android applications.thalesmello

15 Answers

241
votes

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

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)
            }
        }
    }
}
29
votes

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

19
votes

Have you tried PaperParcel? It's an annotation processor which automatically generates the Android Parcelable boilerplate code for you.

Usage:

Annotate your data class with @PaperParcel, implement PaperParcelable, and add a JVM static instance of the generated CREATOR e.g.:

@PaperParcel
data class Example(
  val test: Int,
  ...
) : PaperParcelable {
  companion object {
    @JvmField val CREATOR = PaperParcelExample.CREATOR
  }
}

Now your data class is Parcelable and can be passed directly to a Bundle or Intent

Edit: Update with latest API

16
votes

The best way with no boilerplate code at all is Smuggler gradle plugin. All you need is just implement AutoParcelable interface like

data class Person(val name:String, val age:Int): AutoParcelable

And that's all. Works for sealed classes as well. Also this plugin provides compile time validation for all AutoParcelable classes.

UPD 17.08.2017 Now with Kotlin 1.1.4 and Kotlin Android extensions plugin you could use @Parcelize annotation. In this case, the example above will look like:

@Parcelize class Person(val name:String, val age:Int): Parcelable

No need for data modifier. The biggest downside, for now, is using kotlin-android-extensions plugin which has a lot of other functions that could be unnecessary.

12
votes
  • Use @Parcelize annotation on top of your Model / Data class
  • Use latest version of Kotlin
  • Use latest version of Kotlin Android Extensions in your app module

Example :

@Parcelize
data class Item(
    var imageUrl: String,
    var title: String,
    var description: Category
) : Parcelable
6
votes

Using Android Studio and the Kotlin plugin, I found an easy way to convert my old Java Parcelables with no extra plugins (if all you want is to turn a brand new data class into a Parcelable, skip to the 4th code snippet).

Let's say you have a Person class with all the Parcelable boiler plate:

public class Person implements Parcelable{
    public static final Creator<Person> CREATOR = new Creator<Person>() {
        @Override
        public Person createFromParcel(Parcel in) {
            return new Person(in);
        }

        @Override
        public Person[] newArray(int size) {
            return new Person[size];
        }
    };

    private final String firstName;
    private final String lastName;
    private final int age;

    public Person(String firstName, String lastName, int age) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
    }

    protected Person(Parcel in) {
        firstName = in.readString();
        lastName = in.readString();
        age = in.readInt();
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(firstName);
        dest.writeString(lastName);
        dest.writeInt(age);
    }

    @Override
    public int describeContents() {
        return 0;
    }

    public String getFirstName() {
        return firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public int getAge() {
        return age;
    }
}

Start by stripping out the Parcelable implementation, leaving a bare-bones, plain, old Java object (properties should be final and set by the constructor):

public class Person {
    private final String firstName;
    private final String lastName;
    private final int age;

    public Person(String firstName, String lastName, int age) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
    }

    public String getFirstName() {
        return firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public int getAge() {
        return age;
    }
}

Then let the Code > Convert Java file to Kotlin File option do its magic:

class Person(val firstName: String, val lastName: String, val age: Int)

Convert this into a data class:

data class Person(val firstName: String, val lastName: String, val age: Int)

And finally, let's turn this into a Parcelable again. Hover the class name and Android Studio should give you the option to Add Parcelable Implementation. The result should look like this:

data class Person(val firstName: String, val lastName: String, val age: Int) : Parcelable {
    constructor(parcel: Parcel) : this(
            parcel.readString(),
            parcel.readString(),
            parcel.readInt()
    )

    override fun writeToParcel(parcel: Parcel, flags: Int) {
        parcel.writeString(firstName)
        parcel.writeString(lastName)
        parcel.writeInt(age)
    }

    override fun describeContents(): Int {
        return 0
    }

    companion object CREATOR : Parcelable.Creator<Person> {
        override fun createFromParcel(parcel: Parcel): Person {
            return Person(parcel)
        }

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

As you can see, the Parcelable implementation is some auto-generated code appended to you data class definition.

Notes:

  1. Trying to convert a Java Parcelable directly into Kotlin will not produce the same result with the current version of the Kotlin plugin (1.1.3).
  2. I had to remove some extra curly braces the current Parcelable code generator introduces. Must be a minor bug.

I hope this tip works for you as well as it did for me.

5
votes

You can do it using @Parcelize annotation. It is an automatic Parcelable implementation generator.

First, you need to enable them adding this to your module's build.gradle:

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

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

You DONT need to add experimental = true inside androidExtensions block.

4
votes

I will leave my way of doing in case it might help someone.

What i do is i have a generic Parcelable

interface DefaultParcelable : Parcelable {
    override fun describeContents(): Int = 0

    companion object {
        fun <T> generateCreator(create: (source: Parcel) -> T): Parcelable.Creator<T> = object: Parcelable.Creator<T> {
            override fun createFromParcel(source: Parcel): T = create(source)

            override fun newArray(size: Int): Array<out T>? = newArray(size)
        }

    }
}

inline fun <reified T> Parcel.read(): T = readValue(T::class.javaClass.classLoader) as T
fun Parcel.write(vararg values: Any?) = values.forEach { writeValue(it) }

And then i create parcelables like this:

data class MyParcelable(val data1: Data1, val data2: Data2) : DefaultParcelable {
    override fun writeToParcel(dest: Parcel, flags: Int) { dest.write(data1, data2) }
    companion object { @JvmField final val CREATOR = DefaultParcelable.generateCreator { MyParcelable(it.read(), it.read()) } }
}

Which gets me rid of that boilerplate override.

3
votes

Unfortunately there is no way in Kotlin to put a real field in an interface, so you can't inherit it from an interface-adapter for free: data class Par : MyParcelable

You may look at delegation, but it does not help with fields, AFAIK: https://kotlinlang.org/docs/reference/delegation.html

So the the only option I see is a fabric function for Parcelable.Creator, which is kind of obvious.

2
votes

i prefer just using the https://github.com/johncarl81/parceler lib with

@Parcel(Parcel.Serialization.BEAN)
data class MyClass(val value)
2
votes

A simpler and up-to-date method would be to use the @Parcelize annotation which removes the hard word work of implementing the Parcelable

build.gradle (app module)

apply plugin: "kotlin-parcelize"

// If you are using the new plugin format use this instead.
plugins{
    ...
    id "kotlin-parcelize"
}

YourClass.kt

import kotlinx.parcelize

@Parcelize
class User(val firstName: String, val lastName: String, val age: Int): Parcelable
1
votes

Kotlin has made the entire process of Parcelization in Android damn easy with its @Parcel annotation.

To do that

Step 1. Add Kotlin extensions in your app module gradle

Step 2. Add experimental = true since this feature is still in experimentation in gradle.

androidExtensions { experimental = true }

Step 3. Annonate the data class with @Parcel

Here is an simple example on @Parcel usage

1
votes

Below Kotlin code can help you to create Parcelable data classes with Parent and Child Data class

Parent Data Class - MyPostModel

data class MyPostModel(
    @SerializedName("post_id") val post_id: String? = "",
    @SerializedName("category_id") val category_id: String? = "",
    @SerializedName("images") val images: ArrayList<ImagesModel>? = null
) : Parcelable {
    constructor(parcel: Parcel) : this(
        parcel.readString(),
        parcel.readString(),
        parcel.createTypedArrayList(ImagesModel.CREATOR)
    )

    override fun writeToParcel(parcel: Parcel, flags: Int) {
        parcel.writeString(post_id)
        parcel.writeString(category_id)
        parcel.writeTypedList(images)
    }

    override fun describeContents(): Int {
        return 0
    }

    companion object CREATOR : Parcelable.Creator<MyPostModel> {
        override fun createFromParcel(parcel: Parcel): MyPostModel {
            return MyPostModel(parcel)
        }

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

Child Data Class - ImagesModel

data class ImagesModel(
    @SerializedName("image_id") val image_id: String? = "",
    @SerializedName("image_url") val image_url: String? = ""
) : Parcelable {
    constructor(parcel: Parcel) : this(
        parcel.readString(),
        parcel.readString()
    )

    override fun writeToParcel(parcel: Parcel, flags: Int) {
        parcel.writeString(image_id)
        parcel.writeString(image_url)
    }

    override fun describeContents(): Int {
        return 0
    }

    companion object CREATOR : Parcelable.Creator<ImagesModel> {
        override fun createFromParcel(parcel: Parcel): ImagesModel {
            return ImagesModel(parcel)
        }

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

There is a Plugin but is not always as updated as Kotlin is evolving: https://plugins.jetbrains.com/plugin/8086

Alternative: I have a working example of a custom data class using Parcelable and lists:

Data classes using Parcelable with Lists:

https://gist.github.com/juanchosaravia/0b61204551d4ec815bbf

Hope it helps!