You are going to delete lots of lines of code! Yes, it is not a clickbait!
How do you pass your model between activities?
- EventBus / Otto ?
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.
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.
Kotlin version 1.1.4 or newer
How To Use:
Add the code below into your gradle.
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.
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.
If you liked the article, please clap it. Thanks!