540grunkspin
02/21/2019, 8:55 AMParcel.readSparseArray
. It returns SparseArray
without any generic parameter and I am not aware of a way to read it with the generic parameter. It should be fairly easy to reify that one to do a cast for you. I know that this is not something that is super hard to do yourself but it feels like a hack every time i need to suppress the unchecked cast warning.gildor
02/21/2019, 8:59 AMbut it feels like a hack every time i need to suppress the unchecked cast warningYou also can write extension function to encapsulate this behavior
540grunkspin
02/21/2019, 9:03 AMgildor
02/21/2019, 9:03 AM540grunkspin
02/21/2019, 9:06 AM@Trows
annotation. Or return a SparseArray?
gildor
02/21/2019, 9:07 AM@Throws
is useless, this annotation make sense only for Java interop540grunkspin
02/21/2019, 9:08 AMgildor
02/21/2019, 9:11 AMval input = SparseArray<Any>()
input.put(0, "String!") // Put string
a.writeSparseArray(input)
val output = a.readSparseArray(javaClass.classLoader) as SparseArray<Int> // No exception here!
val item: Int = output.get(0) // Exception will happen here!
a.readSparseArray(javaClass.classLoader) as SparseArray<Int>
to function this function will return successfully, but cast will fail540grunkspin
02/21/2019, 9:13 AMgildor
02/21/2019, 9:13 AM540grunkspin
02/21/2019, 9:14 AMreadUncheckedSparseArray
gildor
02/21/2019, 9:22 AMinline fun <reified T> Parcel.readAndCastSparseArray(): SparseArray<T>? {
val sparseArray = readSparseArray(javaClass.classLoader) ?: return null
for (index in 0 until sparseArray.size()) {
val value = sparseArray.valueAt(index)
if (value != null && value !is T) {
throw ClassCastException("Value $value on index $index cast failed to ${T::class}")
}
}
@Suppress("UNCHECKED_CAST")
return sparseArray as SparseArray<T>
}
540grunkspin
02/21/2019, 10:24 AM