Skip to content

Type Adapters

Bradley Campbell edited this page Apr 11, 2016 · 8 revisions

Occasionally when using PaperParcel you might find the need to parcel an unknown type, or modify how an object is read/written to a parcel. TypeAdapters allow you to do this.

A good example of when you might want this functionality is with java.util.Date objects. By default, PaperParcel will recognise Date as Serializable, and use Serialization as the Parcel reading/writing mechanism. Serialization is slow, so you might want to write a custom TypeAdapter for a Date.

Defining TypeAdapters for a particular type automatically allows the use of this type with any container type, e.g. a TypeAdapter for Date will apply to the Date elements in List<Map<String, Date>>.

class DateTypeAdapter : TypeAdapter<Date> {
    override fun writeToParcel(value: Date, outParcel: Parcel, flags: Int) {
        outParcel.writeLong(value.time)
    }

    override fun readFromParcel(inParcel: Parcel): Date {
        return Date(inParcel.readLong())
    }
}

TypeAdapters can be applied in multiple ways:

Default TypeAdapters

Annotate your type adapter with @DefaultAdapter:

@DefaultAdapter 
class DateTypeAdapter : TypeAdapter<Date> {
  // ... 
}

In this example, PaperParcel will automatically use this TypeAdapter for any Date type unless a more explicit TypeAdapter is defined later.

Class TypeAdapters

Add the list of specific TypeAdapters to the data class. This will take precedence over global TypeAdapters and will apply to all variables in this class of the specified type.

@PaperParcel
@TypeAdapters(DateTypeAdapter::class)
data class Example(
  val a: Date
) : PaperParcelable { ... }

Variable TypeAdapters

Add the list of specific TypeAdapters directly on the variable. These will take precedence over both global and class-scoped TypeAdapters and will only apply to the annotated variable.

@PaperParcel
data class Example(
  @TypeAdapters(DateTypeAdapter::class) val a: Date
) : PaperParcelable { ... }
Clone this wiki locally