Yet Another Awesome Kotlin Feature: Parcelize

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 clap it. Thanks!


Yet Another Awesome Kotlin Feature: Parcelize was originally published in AndroidPub on Medium, where people are continuing the conversation by highlighting and responding to this story.

Gurupriyan is a Software Engineer and a technology enthusiast, he’s been working on the field for the last 6 years. Currently focusing on mobile app development and IoT.

Please follow and like us:
0