— Kotlin, Parcelize — 1 min read
If you've ever tried to pass custom objects between activities or fragments in your Android app, you may have run into the issue of having to make them Parcelable. In order for an object to be passed as an extra in an Intent or a Bundle, it needs to be serializable, and Parcelable is one way of achieving that. However, writing the Parcelable implementation for a class can be tedious and error-prone, especially if the class has many properties. Fortunately, Kotlin provides a more convenient solution with the @Parcelize
annotation.
The @Parcelize
annotation is part of the kotlinx.android.parcel library, which is included in the Android Gradle plugin by default. When you annotate a data class with @Parcelize
, the compiler generates a Parcelable implementation for it automatically. Here's an example:
1import android.os.Parcelable2import kotlinx.android.parcel.Parcelize3
4@Parcelize5data class User(val name: String, val age: Int) : Parcelable
That's it! You don't need to write any boilerplate code to implement Parcelable anymore. You can now pass instances of User
between activities or fragments using Intents or Bundles, like this:
1val intent = Intent(this, ProfileActivity::class.java)2intent.putExtra("user", user)3startActivity(intent)
In the receiving activity or fragment, you can retrieve the User
instance like this:
1val user = intent.getParcelableExtra<User>("user")
You can also use @Parcelize
with classes that have properties of other Parcelable types, or collections of Parcelable types. The compiler will generate the necessary code to serialize and deserialize them as well.
1@Parcelize2data class Book(val title: String, val author: String, val pages: Int, val reviews: List<Review>) : Parcelable3
4@Parcelize5data class Review(val rating: Int, val comment: String) : Parcelable
In addition to saving you the hassle of writing Parcelable implementations, @Parcelize
also generates more efficient code than the default implementation. When you use the default implementation, each property needs to be written and read individually from the Parcel, which can be slow for large objects. With @Parcelize
, the generated code writes and reads the whole object in one go, making it faster and more efficient.
One thing to note about @Parcelize
is that it only works with data classes, not regular classes or sealed classes. If you need to make a regular class Parcelable, you'll still need to write the implementation manually.
In conclusion, the @Parcelize
annotation is a powerful tool for simplifying Parcelable implementation in Kotlin Android apps. By using it, you can save time and reduce the likelihood of errors in your code. Give it a try in your next project!