You are on page 1of 1

1.

Reading from a Parcel: Here, you add a second constructor (as opposed to the
primary constructor in the class declaration) so a TaskList object can be created
from a passed-in Parcel.

The constructor grabs the values from the Parcel for the title (by calling
readString on the Parcel) and the list of tasks (by calling
createStringArrayList on the Parcel), then passes them into the primary
constructor using this().

Note that readString() and createStringArrayList() return optionals. You


know that the objects a TaskList expect are a string and an ArrayList of strings,
so you use the non-null assertion operator (!!) to get the non-optional values.

2. Writing to a Parcel: This method is called when a Parcel needs to be created


from the TaskList object. The parcel being created is handed into this function,
and you fill it in with the appropriate contents using the assorted write...
functions.

3. Fulfilling static interface requirements: The Parcelable protocol requires


you to create a public static Parcelable.Creator<T> CREATOR field and
override some methods in it using Java. However, static methods don’t exist in
Kotlin. Instead, you create a companion object meeting the same requirements
and override the appropriate functions within that object.

4. Calling your constructor: In the CREATOR companion object, you override the
interface function createFromParcel, and pass the parcel you get from this
function along to the second constructor you just created, giving back a nice new
TaskList with all of the data from the Parcel.

With the Parcelable interface implemented, any TaskList can be passed through an
Intent.

You might also like