How Kotlin’s @Parcelize makes it faster to pass data between Android Components?

Ramakrishna Joshi
2 min readJul 9, 2018
Src: GoogleImages

Primitive values in Android can be sent along with the Intent from one Android component to another but Android does not support sending custom data objects(custom data types) via the Intent. This is where Parcelable Interface comes into picture.

Parcelable Interface is used to send data objects from one android component to another. In order to make a data object class Parcelable, the class has to implement Parcelable Interface and override few functions, primarily writeToParcel(Parcel parcel, int flags) and createFromParcel(Parcel in) which leads to writing lots of boilerplate code.

Also once a class is made parcelable, modifying it requires updating the implemented functions as well.

The below code illustrates how to make a simple model class parcelable using Parcelable in Java ( Traditional way ).

Lots of boilerplate code to transfer a simple object to another activity, right? This is where Kotlin’s @Parcelize reduces the time and effort needed to make a data class Parcelable.

All you need to do is add @Parcelize annotation to the data class to make it Parcelable.

Since this is still in expermental stage you need to add the following in your app level gradle and make sure that you are using latest version of Kotlin(current version is 1.2.41 at the time of writing this article).

androidExtensions {
experimental = true
}

Here is the Parcelable Data Class created by adding @Parcelize in Kotlin

@Parcelize
data class StudentDataClass(
val studentId: String,
val studentName : String,
) : Parcelable {}

That’s all. You can send your data object from source activity like this…

val intent: Intent = Intent(this, SecondActivity::class.java)
intent.putExtra("student_details", StudentDataClass("s1", "Ram"));
startActivity(intent)

and receive the data in your destination activity through the Intent like this…

val intent: Intent = getIntent()
var studentDataClass : StudentDataClass = intent.getParcelableExtra("student_details")

Anything Java can do, Kotlin can do it better in fewer lines.

Pretty smooth and also easy to debug , isn’t it? Let me know if you face any difficulties in the comment section and don’t forget to give claps if this article helps you.

--

--

Ramakrishna Joshi

Mobile App Developer, focusing on Android @ Falabella INDIA | Travel enthusiast | Always on a journey to learn new things!