Sobes.tech
Junior — Middle

Is it possible to save a data class object in an Android Bundle?

sobes.tech AI

Answer from AI

A data class object in Kotlin can be stored in an Android Bundle, but not directly, as Bundle only supports certain data types (primitives, Serializable, Parcelable, etc.).

To store a data class in a Bundle, you need to:

  • Make the data class implement the Parcelable interface (recommended for Android).
  • Or make the data class Serializable (less efficient).

Example with Parcelable (using Kotlin Android Extensions plugin or Parcelize library):

@Parcelize
data class User(val name: String, val age: Int) : Parcelable

// Saving to Bundle
val bundle = Bundle()
bundle.putParcelable("user_key", user)

// Retrieving from Bundle
val user = bundle.getParcelable<User>("user_key")

If the data class does not implement Parcelable or Serializable, it cannot be saved directly into a Bundle.

Is it possible to save a data class object in an… - sobes.tech