SoFunction
Updated on 2025-04-07

kotlin annotation @Parcelize usage examples and steps detailed explanation

In Kotlin,@ParcelizeAnnotations are used to simplify implementation of AndroidParcelableThe process of interface.ParcelableInterfaces are a way in Android for passing objects between components. Usually, implementParcelableThe interface requires a lot of boilerplate code to be written, but uses@ParcelizeAnnotations can greatly simplify this process.

The following is used@ParcelizeAnnotation steps and examples:

1. Add dependencies

First, make sure you add the necessary dependencies to your project. In yourTo the file, add the following plug-in:

apply plugin: 'kotlin-parcelize'
// orplugins {
    id 'kotlin-parcelize'
}
// Notice!!!! kotlin-android-extensions Method is abandoned! Don't use it again!

2. Use @Parcelize annotation

Add on your Kotlin data class@ParcelizeAnnotation and implementationParcelableinterface. Examples are as follows:

import 
import 
@Parcelize
data class User(
    val id: Int,
    val name: String,
    val email: String
) : Parcelable

3. Enable the Parcelize function

existEnable the Parcelize function in the file:

android {
    ...
    kotlinOptions {
        jvmTarget = '1.8'
    }
}

Sample code analysis

In the example above:

  • @ParcelizeAnnotations are used to instruct the compiler to generate the requiredParcelableaccomplish.
  • data class UserIt is a data class with three attributes:idnameandemail
  • UserThe class has been implementedParcelableInterface, this is through@ParcelizeAnnotations are automatically completed.

Using Parcelable objects

When you need to pass this in the IntentUserWhen using an object, you can do this:

Passing objects

val user = User(1, "John Doe", "@")
val intent = Intent(this, AnotherActivity::)
("user_key", user)
startActivity(intent)

Receive object

val user = <User>("user_key")

This way, you can easily pass complex objects between different Android components such as Activity and Fragment without having to write them manuallyParcelableImplement code.

Things to note

  • use@ParcelizeWhen , make sure that all attribute types support Parcelable or serialization.
  • Check your Kotlin version,@ParcelizeHas been moved to the newer Kotlin versionPack it, not the old oneBag.

Through these steps, you can use@ParcelizeSimplified annotationParcelableThe implementation greatly reduces the workload of manually writing boilerplate code.

This is the article about kotlin annotation @Parcelize used. This is all about this article. For more related kotlin annotations @Parcelize content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!