DEV Community

Bigyan Thapa
Bigyan Thapa

Posted on

Parcelize in Android using kotlin-android-extensions

With kotlin-android-extensions we can implement Parcelable in much simpler way using @Parcelize and Parcelable.

Enable android extensions in app gradle file

Android extensions are not considered production-ready yet, so we need to turn experimental mode on in app's build.gradle file

androidExtensions {
  experimental = true
}

Parcelize simple class or data class

For this we need to annotate the class with @Parcelize and implement Parcelable. @Parcelize annotation requires all serializable properties be declared in the primary constructor.
e.g.

@Parcelize
class Book(val author: String, val price: Int): Parcelable

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

More advanced serialization logic can be written inside a companion object:

@Parcelize
data class Book(val author: String, val price: Int) : Parcelable {
  private companion object: Parceler<Book> {
    override fun Book.write(parcel: Parcel, flags: Int) {
      // add custom write here
    }
    override fun create(parcel: Parcel): Book {
      // add custom read here
    }
  }
}

Parcelize enums

Enum can also be parcelized starting kotlin-version:1.2.60. This is similar to parcelizing the data classes.

@Parcelize
enum class BookType: Parcelable { HISTORY, DRAMA, FICTION, BIO }

Parcelize sealed classes

sealed and abstract classes can also be parcelized. For this, the parent class needs to implement Parcelable and all the child classes need to be annotated with @Parcelize. e.g.

sealed class Result : Parcelable {

  @Parcelize
  object Failure : Result

  @Parcelize
  object Error : Result

  @Parcelize
  class Success : Result
}

Please leave feedback in the comments.

Top comments (3)

Collapse
 
lawloretienne profile image
Etienne Lawlor

I tried getting this set up but it doesnt recognize the import
import kotlinx.android.parcel.Parcelize
Is there something else that needs to be set up?

Collapse
 
lawloretienne profile image
Etienne Lawlor

so i figured it out

this is the correct order for the plugins
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
i had it in reverse which is why it wasnt working

Collapse
 
bigyan4424 profile image
Bigyan Thapa

Sorry for not being able to promptly reply. I am glad you figured it out. And the order matters and that is the right order.