Parcelable: The lazy coder’s way
@Parcelize class Item( var imageId: Int, var title: String, var details: String, var price: Double, var category: Category, var postedOn: Long ) : Parcelable
See, easy as that! All you need is just to confirm followings:
- Use @Parcelize annotation on top of your Model / Data class
- Use latest version of Kotlin (v1.1.51 at the time of writing this article)
- Use latest version of Kotlin Android Extensions in your app module, so your build.gradle may look like:
apply plugin: 'com.android.application' apply plugin: 'kotlin-android' apply plugin: 'kotlin-android-extensions' android { ... ... ... // Add for using latest experimental build of Android Extensions androidExtensions { experimental = true } } dependencies { ... ... ... }
Passing the Parcelable
val intent = Intent(this, AnotherActivity::class.java) intent.putExtra("extra_item", item)
Retrieving the Parcelable
val item = intent.getParcelableExtra("extra_item") // Do something with the item (example: set Item title and price)
That’s all for now. Stay Lazy and Productive.
Happy coding!!