Yet Another Awesome Kotlin Feature: Parcelize

Burak Eregar
AndroidPub
Published in
2 min readDec 2, 2017

--

You are going to delete lots of lines of code! Yes, it is not a clickbait!

How do you pass your model between activities?

  • Serializable?
  • EventBus / Otto ?
  • Parcelable?

Serializable = Reflection! Run Forest Run!!! It is terrible for Android performance.

Bus libraries like EventBus or Otto are easy to use and have good performance but after some time they cause too much complexity in your code.

Parcelable interface is great for Android performance but it has too much boilerplate.

Parcelize 😍

Kotlin added parcelable support in version 1.1.4.

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.

Java model vs Kotlin model

I have created two samples of the exact same class with Java and with Kotlin using Parcelable.

Student.java

Student.kt 😍

Prerequisites:

Kotlin version 1.1.4 or newer

How To Use:

Add the code below into your gradle.

androidExtensions {
experimental = true
}

You also need to add apply plugin: ‘kotlin-android-extensions’ to your gradle file. However, if you have created your project using Kotlin support, it should be added automatically.

Then add @Parcelize annotation to your model. That’s it! You don’t need to write any parcel methods anymore!

Our awesome Kotlin model looks like below:

About Lint Error

Android Studio gives the Lint error below right now. It is a reported bug to IntelliJ. You can find the corresponding issue in the link below.

https://youtrack.jetbrains.com/issue/KT-19300

You can run your project without any errors so you can just ignore the Lint error for now.

Please find the sample project for Kotlin Parcelize in the link below.

https://github.com/burakeregar/KotlinParcelize

If you liked the article, please don’t forget to clap it :)

You can also follow me on Twitter and GitHub
https://twitter.com/burakeregar

https://github.com/burakeregar

Thanks!

--

--