lannyf
lannyf

Reputation: 11035

How to use generic list for putParcelableArrayList?

Using kotlin, and having a function takes a generic list, and inside the lis is put in a Bundle to pass to a fragment.

fun createArgs(filters: List<Filters>?): Bundle {
    val args = Bundle()
    args.putParcelableArrayList(KEY_FILTERS, filters)  //<=== does not compile

has to change to

args.putParcelableArrayList(KEY_FILTERS, ArrayList(filters))

which making another copy of the list.

How to set a generic list into Bundle?

Upvotes: 0

Views: 786

Answers (2)

Alexey Romanov
Alexey Romanov

Reputation: 170815

In most cases (but not always) List instances are actually ArrayLists. So you can avoid most copies:

fun <T> List<T>.asArrayList(): ArrayList<T> = if (this is ArrayList) this else ArrayList(this)

args.putParcelableArrayList(KEY_FILTERS, filters.asArrayList())

Bundle won't mutate the list you put into it, so this should be safe enough assuming you don't mutate it either after putting it into the bundle.

Upvotes: 1

CommonsWare
CommonsWare

Reputation: 1007296

How to set a generic list into Bundle?

You don't. Bundle is limited to only certain types, and List is not one of them.

Upvotes: 3

Related Questions