How to parcel List<Int> with kotlin
You can write a list of integers as int[]
:
parcel.writeIntArray(files.toIntArray())
Make sure you use the same data structure when reading back:
files = parcel.createIntArray().toList()
You could make it more efficient using extension functions by skipping the array representation:
parcel.writeIntList(files)
files = parcel.createIntList()
fun Parcel.writeIntList(input:List<Int>) {
writeInt(input.size) // Save number of elements.
input.forEach(this::writeInt) // Save each element.
}
fun Parcel.createIntList() : List<Int> {
val size = readInt()
val output = ArrayList<Int>(size)
for (i in 0 until size) {
output.add(readInt())
}
return output
}
Kotlin's @Parcelize
annotation handles lists; you just need to make sure the list items implement the Parcelable
interface as well:
@Parcelize
data class MyDataClass(
val items: List<MyListItem>?
) : Parcelable
@Parcelize
data class MyListItem(
var type: String?,
var itemId: Long = 0
) : Parcelable