Skip to content

Type Adapters

Bradley Campbell edited this page Nov 27, 2016 · 8 revisions

Important: all information in this on this page is only relevant to PaperParcel 1.x. For information on the latest version of PaperParcel, visit http://grandstaish.github.io/paperparcel/

Overview

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>>.

How to define a TypeAdapter:

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())
    }
}

This example is defined as a class, but TypeAdapters can also be defined as kotlin objects

How to apply a TypeAdapter:

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
) 

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
) 
Clone this wiki locally